在我的SQL代码中获得MAX客户的最佳方法

时间:2019-05-16 19:34:37

标签: sql max

对于每种产品,我需要了解在一段时间内哪个客户的库存量最大。我只希望每个产品1位顾客返回我的结果。我知道我应该在QtyShip上使用MAX,但是我无法将头部缠绕在哪里。在子查询中?

我从下面的代码开始。有人可以告诉我我在这里投入最大的机会吗?

Select o.cono ,
o.ProdId ,
o.CustId ,
c.[name] as 'CustomerName' ,
s.shipto ,
s.[name] as 'ShiptoName' ,
s.user15 as 'divno' ,
o.WhseId ,
SUM(NetAmt) as 'totalNet' ,
SUM(cost) as 'totalCost' ,
SUM(QtyShip) as 'totalQtyShip'
FROM Order_Line_Invoice o
LEFT JOIN ARSC c
    on  o.cono = c.cono
        and o.CustId = c.custno
        and c.insx = 1
LEFT JOIN ARSS s
    on  o.cono = s.cono
        and o.CustId = s.custno
        and o.ShipToId = s.shipto
        and s.insx = 1
GROUP BY o.cono ,
o.ProdId ,
o.CustId ,
c.[name] ,
s.shipto ,
s.[name] ,
s.user15 ,
o.WhseId

2 个答案:

答案 0 :(得分:1)

您可以使用大多数dbms支持的row_number()

    with cte as
    (
    Select o.cono ,
    o.ProdId ,
    o.CustId ,
    c.[name] as CustomerName,
    s.shipto ,
    s.[name] as ShiptoName ,
    s.user15 as 'divno ,
    o.WhseId ,
    SUM(NetAmt) as totalNet ,
    SUM(cost) as totalCost ,
    SUM(QtyShip) as totalQtyShip
    FROM Order_Line_Invoice o
    LEFT JOIN ARSC c
        on  o.cono = c.cono
            and o.CustId = c.custno
            and c.insx = 1
    LEFT JOIN ARSS s
        on  o.cono = s.cono
            and o.CustId = s.custno
            and o.ShipToId = s.shipto
            and s.insx = 1
    GROUP BY o.cono ,
    o.ProdId ,
    o.CustId ,
    c.[name] ,
    s.shipto ,
    s.[name] ,
    s.user15 ,
    o.WhseId
    ),
    cte2 as
   (
   select *,row_number()over(partition by ProdId order by totalQtyShip desc) rn
   from cte
 ) select * form cte2 where rn=1

答案 1 :(得分:0)

尝试 SELECT 前1名(此处其余查询)
然后添加 ORDER BY SUM(QtyShip)描述 到最后