如何在 sql 中找到客户类别中的最大产品 ID?

How to find the maximum product id in customer wise category in sql?

这里我有客户 ID 和最大订单数量,如何获得最大订单数量的 productid 列以及 customerid 和 maxorderqty 列。

数据库:冒险作品
表 used:salesorerheader、销售订单详细信息

SELECT customerid,
       Max(totalqty)
FROM   (SELECT customerid,
               Sum(orderqty) AS Totalqty,
               productid     AS pdtid
        FROM   sales.salesorderheader a
               INNER JOIN sales.salesorderdetail b
                       ON a.salesorderid = b.salesorderid
        GROUP  BY customerid,
                  productid)A
WHERE  customerid = 29825
GROUP  BY customerid

如果您对查找单条记录感兴趣,可以使用如下方式:

SELECT TOP(1) CustomerID, max(totalqty) AS maxqty, pdtid
FROM
(
  SELECT customerid, Sum(orderqty) AS Totalqty, productid AS pdtid
  FROM   sales.salesorderheader a
    INNER JOIN sales.salesorderdetail b
      ON a.salesorderid = b.salesorderid
  GROUP  BY customerid, productid
) A
WHERE CustomerID=29825
GROUP BY CustomerID, pdtid
ORDER BY max(totalqty) DESC

但是......如果你想找到几条排名相同的记录,使用这个:

SELECT *
FROM 
(
  SELECT RANK() OVER(ORDER BY max(totalqty) DESC) rnk, CustomerID, max(totalqty) AS maxqty, pdtid
  FROM
  (
    SELECT customerid, Sum(orderqty) AS Totalqty, productid AS pdtid
    FROM   sales.salesorderheader a
      INNER JOIN sales.salesorderdetail b
        ON a.salesorderid = b.salesorderid
    GROUP  BY customerid, productid
  ) A
  WHERE CustomerID=29825
  GROUP BY CustomerID, pdtid
) B
WHERE rnk = 1

db<>fiddle

另一种方法是再次 'join' 航行详情 ;)