返回具有列的最大值的行

时间:2015-03-06 08:09:44

标签: sql tsql

我有一张看起来像这样的表:

date       | product | price
--------------------------------
17/01/2015 | milk    | 2.54
18/01/2015 | milk    | 2.47
23/01/2015 | milk    | 2.61
21/01/2015 | eggs    | 1.35
04/02/2015 | eggs    | 1.36
27/01/2015 | eggs    | 1.31

我需要的是一个选项,它会返回每个产品的最新价格,即具有最大日期的产品。这里的期望结果将是:

23/01/2015 | milk    | 2.61
04/02/2015 | eggs    | 1.36

我试过了:

select max(date), product, price FROM table GROUP BY product, price

但它没有按预期工作。

5 个答案:

答案 0 :(得分:1)

使用相关子查询查找每个产品的上一个日期:

select date, product, price
from table t1
where date = (select max(date) from table t2
              where t1.product = t2.product)

(在阅读Damien_The_Unbeliever的评论后,我想补充一点,如果存在多个产品的最大日期相同的条目,它们将全部返回。)

答案 1 :(得分:0)

试试这样:

select max(date), product,price
from table
group by product, price

答案 2 :(得分:0)

您可以使用ROW_NUMBER()中的MS SQL来完成此操作。

DECLARE @TABLE TABLE([Date] DATE, Product VARCHAR(40), Price DECIMAL(18,2))

INSERT INTO @TABLE VALUES
('01/17/2015', 'milk', '2.54'),
('01/18/2015', 'milk', '2.47'),
('01/23/2015', 'milk', '2.61'),
('01/21/2015', 'egg', '1.35'),
('02/04/2015', 'egg', '1.36'),
('01/27/2015', 'egg', '1.31')

SELECT * FROM 
(
    SELECT ROW_NUMBER() OVER (PARTITION BY Product ORDER BY [Date] DESC) RN, Product, Price
     FROM @TABLE
)  Temp
WHERE RN = 1  

答案 3 :(得分:0)

试试这个:

   SELECT tb.*
FROM table tb
INNER JOIN
    (SELECT  MAX(date), product AS MaxDateTime
    FROM table
    GROUP BY product) groupedtb 
ON tb.product = groupedtb.product 
AND tb.date = groupedtb.MaxDateTime

答案 4 :(得分:0)

我知道你已经得到了答复,但这也有效:)

            DECLARE @TableProducts TABLE (
            [date] DATE,
            Product VARCHAR(100),
            Price NUMERIC(9,2)
            );

            INSERT INTO @TableProducts
            VALUES 
            ('17/01/2015', 'milk', 2.54),
            ('18/01/2015', 'milk', 2.47),
            ('23/01/2015', 'milk', 2.61),
            ('21/01/2015', 'eggs', 1.35),
            ('04/02/2015', 'eggs', 1.36),
            ('27/01/2015', 'eggs', 1.31);


            SELECT B.Product, B.Price, A.MostRecentDate
            FROM (
                    SELECT Product, MAX([date]) AS MostRecentDate
                    FROM @TableProducts
                    GROUP BY Product
            ) AS A
            INNER JOIN @TableProducts AS B  ON A.Product = B.Product
                                            AND A.MostRecentDate = B.[date];