T-SQL:与一个表或另一个表进行单查询连接

问题描述 投票:0回答:5

我的问题如下: 假设您有三个不同的表(产品、账单和退货)

| ProductId | Name |
=====================
| 1         | Car  |

| BillId | ProductId | Amount |
=================================
| 1      | 1         | 100$   |
| 2      | 1         | 200$   |

| ReturnId | ProductId | Amount |
===================================
| 1        | 1         | 50$    |

单个查询如何获得以下输出:

| Product-ID | Name | Type | Amount |
=====================================
| 1          | Car  | Bill | 100$   |
| 1          | Car  | Bill | 200$   |
| 1          | Car  | Ret  | 50$    |

我尝试过各种连接,但不知何故我无法理解这个问题。 我做错了什么? 到目前为止我找到的最接近的解决方案是这样的:

SELECT p.*,
       (CASE
           WHEN b.Amount IS NOT NULL THEN 'Bill'
           ELSE 'Ret'
       END) AS Type,
       COALESCE(b.Amount, r.Amount) AS Amount
FROM Products p
LEFT JOIN Bills b ON b.ProductId = p.ProductId
LEFT JOIN Returns r ON r.ProductId = p.ProductId

有一件事对我来说非常重要:真正的场景查询要大得多,我不想复制/粘贴查询的整个逻辑,就像使用 Union 时的情况一样。

sql t-sql left-join
5个回答
20
投票

以下内容将根据需要工作,

SELECT  Products.*, 
        [Type], 
        Amount
FROM    Products
        INNER JOIN
        (   SELECT  ProductID, 'Bill' [Type], Amount
            FROM    Bills
            UNION ALL
            SELECT  ProductID, 'Ret' [Type], Amount
            FROM    Returns
        ) transactions
            ON transactions.ProductID = Products.ProductID

6
投票

您可以使用

UNION

SELECT p.*, 'Bill' as [Type], b.Amount
FROM Products p
  INNER JOIN Bills b
    ON b.ProductId = p.ProductId
UNION 
SELECT p.*, 'Ret' as [Type], r.Amount
FROM Products p
  INNER JOIN Returns r
    ON r.ProductId = p.ProductId

1
投票
SELECT *
(SELECT Products.ProductID,
        Products.Name,
        'Bill' as Type,
        Bills.Amount
FROM        Products INNER JOIN Bills
            on Products.ProductID = Bills.ProductID
UNION
SELECT  Products.ProductID,
        Products.Name,
        'Ret' as Type,
        Returns.Amount
FROM        Products INNER JOIN Returns
            on Products.ProductID = Returns.ProductID) as iTable
WHERE   iTable.ProductID = 1

1
投票

尝试 UNION 查询 - 类似

SELECT *, 'bill' FROM 
dbo.product
INNER JOIN bills ON dbo.product.Product_Id = dbo.bills.product_id
UNION
SELECT *, 'return' FROM 
dbo.product
INNER JOIN dbo.returns ON dbo.product.Product_Id = dbo.returns.product_id

1
投票

如果您不喜欢嵌套子查询的外观,您可以采用GarethD 的出色解决方案并将其转换为公共表表达式(CTE)

WITH Transactions AS (
    SELECT ProductID, 'Bill' [Type], Amount FROM Bills
      UNION ALL
    SELECT ProductID, 'Ret'  [Type], Amount FROM Returns
)
SELECT  p.*,  [Type], Amount
FROM    Products p
JOIN    Transactions t
            ON t.ProductID = p.ProductID

这是 SqlFiddle 中的演示

© www.soinside.com 2019 - 2024. All rights reserved.