这是我的表:
使用此查询,我获得了大部分已售商品:
SELECT [Purchased Item], SUM([Overall Quantity purchased] )
FROM ReportDraft
GROUP BY [Purchased Item]
ORDER BY SUM([Overall Quantity purchased] )
这将返回客户购买的物品和总数量。
我可以以某种方式创建一个像
这样的表ItemName | Total quantity purchased | Customer who purchased most | Customer quantity bought
Pie--------|---------11------------|---------------ALEX----------|--------3------------|
谢谢
答案 0 :(得分:2)
我会使用窗口函数和条件聚合:
SELECT [Purchased Item], sum(total) as total,
MAX(CASE WHEN seqnum = 1 THEN Customer END) as customer,
MAX(Total) as max_quantity
FROM (SELECT [Purchased Item], Customer, SUM([Overall Quantity purchased] ) as total,
ROW_NUMBER() OVER (PARTITION BY Customer ORDER BY SUM([Overall Quantity purchased]) DESC) as seqnum
FROM ReportDraft
GROUP BY [Purchased Item], Customer
) rd
GROUP BY [Purchased Item]
ORDER BY SUM([Overall Quantity purchased] );