我有一张名为“付款”的表格如下:
+----+--------+
| ID | Amount |
+----+--------+
| 1 | 1.00 |
| 2 | 3.00 |
| 3 | -15.00 |
| 3 | 20.00 |
+----+--------+
“金额”表示转手的现金 - 正数的记录表示已收到现金,而负数的记录表示现金返还为变更。
以下查询:
SELECT ID
, CASE WHEN Amount >= 0 THEN Amount END AS CashTaken
, CASE WHEN Amount < 0 THEN Amount END AS CashBack
FROM Payments
WHERE TicketID IN ('1', '2', '3')
...给我这个结果集:
+----+-----------+----------+
| ID | CashTaken | CashBack |
+----+-----------+----------+
| 1 | 1.00 | NULL |
| 2 | 3.00 | NULL |
| 3 | NULL | -15.00 |
| 3 | 20.00 | NULL |
+----+-----------+----------+
如何按ID对这些记录进行分组,以便我可以获得以下内容?
+----+-----------+----------+
| ID | CashTaken | CashBack |
+----+-----------+----------+
| 1 | 1.00 | NULL |
| 2 | 3.00 | NULL |
| 3 | 20.00 | -15.00 |
+----+-----------+----------+
我有点尴尬,因为我觉得这很简单,就在我面前。
答案 0 :(得分:2)
您可以尝试使用MIN
,MAX
:
SELECT TicketID
, MAX(CASE WHEN Amount >= 0 THEN Amount END) AS CashTaken
, MIN(CASE WHEN Amount < 0 THEN Amount END) AS CashBack
FROM Payments
WHERE TicketID IN ('1', '2', '3')
GROUP BY TicketID
使用给定数据执行示例:
DECLARE @Payments TABLE (TicketID INT, Amount DECIMAL(5,2));
INSERT INTO @Payments(TicketID, Amount)
SELECT 1, 1.00 UNION
SELECT 2, 3.00 UNION
SELECT 3, -15.00 UNION
SELECT 3, 20.00;
SELECT TicketID
, MAX(CASE WHEN Amount >= 0 THEN Amount END) AS CashTaken
, MIN(CASE WHEN Amount < 0 THEN Amount END) AS CashBack
FROM @Payments
WHERE TicketID IN ('1', '2', '3')
GROUP BY TicketID
结果:
TicketID CashTaken CashBack
---------------------------------
1 1.00 NULL
2 3.00 NULL
3 20.00 -15.00