如何对结果1中的值进行求和,如结果2
Result 1
SalesRep Customer Product Quantity Total
Doe, John AA Corp P1 50 5000
Doe, John CA Corp P2 67 6030
Doe, John EA Corp P3 46 5980
Doe, John GA Corp P2 22 1980
Doe, John HA Corp P3 43 5590
Doe, John IA Corp P1 35 3500 | Sum this two
Doe, John IA Corp P2 24 2160 | make second record 0
Doe, John JA Corp P2 66 5940
Doe, John MA Corp P4 59 7670
Doe, John OA Corp P2 43 3870 | Sum this two
Doe, John OA Corp P4 14 1820 | make second record 0
Doe, John PA Corp P1 89 8900
Result 2
SalesRep Customer Product Quantity TotalPrice
Doe, John AA Corp P1 50 5000
Doe, John CA Corp P2 67 6030
Doe, John EA Corp P3 46 5980
Doe, John GA Corp P2 22 1980
Doe, John HA Corp P3 43 5590
Doe, John IA Corp P1 59 5660
Doe, John IA Corp P2 0 0
Doe, John JA Corp P2 66 5940
Doe, John MA Corp P4 59 7670
Doe, John OA Corp P2 57 5690
Doe, John OA Corp P4 0 0
Doe, John PA Corp P1 89 8900
答案 0 :(得分:3)
有一种可能性,虽然我真的没有看到商业案例。我想这只是一个技术问题:
SELECT
T.SalesRep, T.Customer, T.Product,
CASE WHEN EXISTS (SELECT 1 FROM MyTable AS T1
WHERE T1.SalesRep = T.SalesRep
AND T1.Customer = T.Customer
AND T1.Product < T.Product)
THEN 0
ELSE SUM(T.Quantity) OVER (PARTITION BY T.SalesRep, T.Customer)
END AS Quantity,
CASE WHEN EXISTS (SELECT 1 FROM MyTable AS T1
WHERE T1.SalesRep = T.SalesRep
AND T1.Customer = T.Customer
AND T1.Product < T.Product)
THEN 0
ELSE SUM(T.Total) OVER (PARTITION BY T.SalesRep, T.Customer)
END AS Total
FROM MyTable AS T
对于两个CASE
条款,他们读到:“当同一销售代表和客户的产品记录较少时(这是我的假设?),则将值设为零。否则,总结一下按销售代表和客户分组的所有值。每个销售代表和客户也可以使用两种以上(不同的!)产品。
注意:如果每个销售代表可以有几个相同的产品。和客户一样,这不起作用,你必须比较两个嵌套选择中的其他一些值(例如T1.ID < T.ID
)
请注意:这可能是错误的,因为我必须对您的要求做出一些假设。
答案 1 :(得分:2)
好吧,如果您 reeeeeeally 需要带有零的行,那么您可以这样做:
select salesrep,customer,min(product),sum(quantity) as quantity,sum(price) as totalprice
from results1
group by salesrep,customer
union
select salesrep,customer,max(product),0 as quantity,0 as totalprice
from results1
group by salesrep,customer
having count(1)>1;
技术上没有考虑如果有两个以上(salesrep,customer,product)
三元组会发生什么,但只要MS-SQL具有generate_series()
和{{的等价物,就可以修复1}} PostgreSQL的功能。