gpt4 book ai didi

sql - T-SQL : Single-Query Join with either one Table or another

转载 作者:行者123 更新时间:2023-12-02 19:46:56 24 4
gpt4 key购买 nike

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

| 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

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

最佳答案

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

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

关于sql - T-SQL : Single-Query Join with either one Table or another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9031891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com