如何查询每个组中的指定行

时间:2014-01-14 05:46:58

标签: sql sql-server group-by row

我有一张产品表,每张唱片都有售出的价格,可能会有所不同

+-------+-----+----+
|Product|Price|Date|
+-------+-----+----+
|a      |2    |A   |
+-------+-----+----+
|a      |3    |B   |
+-------+-----+----+
|a      |4    |C   |
+-------+-----+----+
|a      |1    |D   |
+-------+-----+----+
|b      |10   |E   |
+-------+-----+----+
|b      |15   |F   |
+-------+-----+----+
|b      |20   |G   |
+-------+-----+----+

我想通过[产品]选择最大价格行组,如何查询?结果我想要:

+-------+-----+----+
|Product|Price|Date|
+-------+-----+----+
|a      |4    |C   |
+-------+-----+----+
|b      |20   |G   |
+-------+-----+----+

我试过

SELECT Product, Max(Price) as Price FROM TableName GROUP BY Product

但它没有获得[Date]列。

3 个答案:

答案 0 :(得分:1)

试试这个 -

SELECT
    PRODUCT
    ,PRICE
    ,DATE
FROM
 (  SELECT
        PRODUCT
        ,PRICE
    ,   DATE
        , RANK() OVER (PARTITION BY PRODUCT ORDER BY PRICE DESC) AS RANKED_PRICE
    FROM TableName
) RANKED_DATA
WHERE RANKED_PRICE IN (1,2,3....N)

我们正在做的是对按产品分区的行进行排名,并按价格的降序排列。然后我们选择排名为1的行来获得所需的结果。

答案 1 :(得分:0)

select Product, Price, Date
from   TableName p1
where  p1.Price >= all ( 
    select p2.Price
    from   TableName p2
    where  p2.Product = p1.Product )

答案 2 :(得分:0)

如果这是在SQL服务器上,你总是可以使用CTE。

WITH CTE AS
(
SELECT Product, MAX(Price) AS Price
FROM TableName
GROUP BY Product
)
SELECT CTE.Product, CTE.Price, T.Date
FROM CTE
INNER JOIN
TableName T ON CTE.Product = T.Product AND CTE.Price = T.Price

然而,可能有其他可行的选项表现更好,你必须自己验证:)我还没有考虑到你可以在两个记录上有相同价格的产品(不说来自应该考虑的描述)....