SQL views, grouping by most sold items and customers who purchased most

爷,独闯天下 提交于 2020-01-06 04:52:28

问题


This is my table:

Using this query, I am getting most sold items:

SELECT [Purchased Item], SUM([Overall Quantity purchased] )
FROM ReportDraft 
GROUP BY [Purchased Item]
ORDER BY SUM([Overall Quantity purchased] )

This returns items and total quantity purchased by customer.

Can I somehow create a table like

ItemName | Total quantity purchased | Customer who purchased most | Customer quantity bought

Pie--------|---------11------------|---------------ALEX----------|--------3------------|

Thank you


回答1:


I would use window functions and conditional aggregation:

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


来源:https://stackoverflow.com/questions/49500067/sql-views-grouping-by-most-sold-items-and-customers-who-purchased-most

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!