查询每位客户的前20项明智记录

时间:2015-07-14 05:44:14

标签: sql

我有一张桌子销售发票,有itemno,custno和数量,日期。我希望每个客户的前三条记录都有降序排列的项目详细信息(最高销售额(数量))。 意思是说

c1 i1 sum(quantity)
c1 i2 sum(quantity)
c1 i3 sum(quantity)
c2 i2 sum(quantity)
c2 i5 sum(quantity)
c2 i3 sum(quantity)

等等。我知道是否需要澄清

2 个答案:

答案 0 :(得分:0)

对于SQL Server,使用公用表表达式CTE

;WITH SumQty AS -- The data format we wish to display
(
    SELECT CustNo, ItemNo, SUM(Quantity) AS SumQty 
    FROM SalesInvoice
    GROUP BY CustNo, ItemNo
),
Seq AS -- The grouping of customer order by qty of items in descending order
(
    SELECT 
        ROW_NUMBER() OVER (PARTITION BY CustNo ORDER BY SumQty DESC) AS Seq, 
        * 
    FROM SumQty 
)
SELECT 
    CustNo,
    ItemNo,
    SumQty 
FROM Seq
WHERE Seq <= 3 -- Interested on top 3 for each customer only

答案 1 :(得分:0)

您可以尝试这样的事情

SELECT * 
FROM
    (SELECT s.custid, s.itemno, sum(s.quantity) as quantity_new
    FROM Salesinvoice AS s 
    GROUP BY s.custid, s.itemno)
GROUP BY custid, itemno
HAVING COUNT(custid) <= 3 
ORDER BY quantity_new DESC;