sql - 如何在sql中找到客户明智类别中的最大产品ID?
问题描述
在这里,我有客户 ID 和最大订单数量,如何获得最大订单数量的 productid 列以及 customerid 和 maxorderqty 列。
数据库:adventure works
使用的表:salesorerheader,salesorderdetails
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
另一种方法是再次“加入”航行细节;)
推荐阅读
- jquery - 如何使用jQuery从HTML表格的倒数第二行获取单元格值
- firebase - 为社交应用程序创建数据库的大图
- laravel - 使用资源获取所有数据库条目及其关系
- jdbc - next-jdbc:执行多条语句?
- image-segmentation - 如何将 Pascal VOC 2012 分割数据集导入 Google Colab?
- elasticsearch - elasticsearch观察者没有显示正确的时间格式
- reactjs - 如何在 React js 中播放数组中的视频
- r - 将 R 帮助文件小插图作为输出打印到 R HTML 笔记本中
- linux - StreamSets 数据收集器安装
- jquery - 当背景图像加载 JQuery