【问题标题】:SQL Query to get highest values based on one column by grouping on another columnSQL Query 通过对另一列进行分组来获取基于一列的最高值
【发布时间】:2019-07-11 04:38:12
【问题描述】:

我正在运行以下 SQL 查询来选择 https://www.w3schools.com/sql/trysql.asp 中每个产品类别中价格最高的产品

SELECT  p.ProductID, p.productName, p.Price, p.CategoryID, c.CategoryName
FROM [Categories] c
LEFT JOIN [Products] p
ON (c.CategoryID = p.CategoryID)
WHERE Price IN (SELECT Max(Price) FROM Products GROUP BY CategoryID)
ORDER BY p.CategoryID

但是,生成的输出为某些类别(如类别 3 和 4)提供了 2 个结果。为什么会发生这种情况?以及如何修改代码以获得每个代码的最高结果?另外,我如何获得每个类别的最低值?

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    使用row_number()

       slect a.* from (SELECT  p.ProductID, p.productName, p.Price, p.CategoryID, c.CategoryName,
          row_number()over(partition by p.CategoryID order by p.Price desc) rn
        FROM [Categories] c
        LEFT JOIN [Products] p
        ON c.CategoryID = p.CategoryID
        ) a where a.rn=1
    

    【讨论】:

      【解决方案2】:

      APPLY 可能是最简单的方法:

      SELECT p.ProductID, p.productName, p.Price, p.CategoryID, c.CategoryName
      FROM categories c OUTER APPLY
           (SELECT TOP (1) p.*
            FROM Products p
            WHERE p.CategoryID = c.CategoryID
            ORDER BY p.Price DESC
           ) p
      ORDER BY c.CategoryID
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-14
        • 2017-10-28
        • 2017-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-23
        相关资源
        最近更新 更多