SQL views, grouping by most sold items and custome

2019-09-01 16:18发布

问题:

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