SQL视图,按大多数销售商品和购买最多的客户进行分组

时间:2018-03-26 20:28:23

标签: sql tsql window-functions sql-view

这是我的表:

enter image description here

使用此查询,我获得了大部分已售商品:

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------------|

谢谢

1 个答案:

答案 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] );