我的问题如下: 假设您有三个不同的表(产品,票据和退货)
| 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
有一点对我来说非常重要:真正的场景查询要大得多,而且我不想复制/粘贴查询的整个逻辑,就像使用联盟时的情况一样。
答案 0 :(得分:17)
以下内容可根据需要使用,
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
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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
答案 4 :(得分:1)
如果您不喜欢嵌套子查询的外观,可以使用GarethD's great solution并将其转换为公用表表达式(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