1

对于每种产品,我需要知道在一段时间内哪个客户的库存量最大。我只希望每种产品有 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
4

2 回答 2

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
于 2019-05-16T19:52:37.057 回答
1

尝试 SELECT top 1(此处查询的其余部分)
,然后将ORDER BY SUM(QtyShip) Desc 添加到末尾

于 2019-05-16T19:59:36.887 回答