我想写一个存储过程。
在该存储过程中,我想从表中查找重复的行值,并将这些行的sum操作计算到同一个表。
假设我有CustomerSales
表格;
ID SalesRepresentative Customer Quantity
1 Michael CustA 55
2 Michael CustA 10
我需要把桌子变成......
ID SalesRepresentative Customer Quantity
1 Michael CustA 65
2 Michael CustA 0
当我同时找到SalesRepresentative
和Customer
个重复项时,我想要将这些行的所有Quantity
值相加并分配到表的第一行,其他人将会是'0'。
答案 0 :(得分:2)
将重复项聚合到一行:
SELECT min(ID) AS ID, SalesRepresentative, Customer
,sum(Quantity) AS Quantity
FROM CustomerSales
GROUP BY SalesRepresentative, Customer
ORDER BY min(ID)
或者,如果您确实希望结果中包含0
的额外行Quantity
:
SELECT ID, SalesRepresentative, Customer
,CASE
WHEN (count(*) OVER (PARTITION BY SalesRepresentative,Customer)) = 1
THEN Quantity
WHEN (row_number() OVER (PARTITION BY SalesRepresentative,Customer
ORDER BY ID)) = 1
THEN sum(Quantity) OVER (PARTITION BY SalesRepresentative,Customer)
ELSE 0
END AS Quantity
FROM CustomerSales
ORDER BY ID
这大量使用window functions。
没有窗口功能的替代版本:
SELECT min(ID) AS ID, SalesRepresentative, Customer, sum(Quantity) AS Quantity
FROM CustomerSales
GROUP BY SalesRepresentative, Customer
UNION ALL
SELECT ID, SalesRepresentative, Customer, 0 AS Quantity
FROM CustomerSales c
GROUP BY SalesRepresentative, Customer
LEFT JOIN (
SELECT min(ID) AS ID
FROM CustomerSales
GROUP BY SalesRepresentative, Customer
) x ON (x.ID = c.ID)
WHERE x.ID IS NULL
ORDER BY ID