选择具有多个DATETIME值的最长日期

时间:2019-01-21 15:19:34

标签: sql sql-server tsql

我正在从数据库中查找信息,以便在datetime列中找到最新时间。有时候,一天中有很多次流程要结束,而我只想查看当天的最新消息。

我尝试了INNER JOIN语句,但是我返回的是MAX Date。

下面的数据示例:

Time                 |    Product
2019-01-01-22:15     |    CHEESE
2019-01-01-22:35     |    CHEESE
2019-01-02-22:35     |    CHEESE
2019-01-02-22:37     |    CHEESE

显示为

Time                 |    Product
2019-01-01-22:35     |    CHEESE
2019-01-02-22:37     |    CHEESE

这将适用于多种产品

*编辑*

我需要一个月的多个日期

*编辑* 当天将用于其他产品,奶酪就是其中的一个例子

所以:

 Time                 |    Product
    2019-01-01-22:15     |    CHEESE
    2019-01-01-22:35     |    CHEESE
    2019-01-01-22:45     |    BREAD
    2019-01-01-22:57     |    BREAD
    2019-01-02-22:35     |    CHEESE
    2019-01-02-22:37     |    CHEESE
    2019-01-02-22:35     |    BREAD
    2019-01-02-22:37     |    BREAD

显示为

Time                 |    Product
2019-01-01-22:35     |    CHEESE
2019-01-01-22:57     |    BREAD
2019-01-02-22:37     |    CHEESE
2019-01-02-22:37     |    BREAD

4 个答案:

答案 0 :(得分:3)

为什么这还不够?

select product, max(time)
from table t
group by product, cast(t.time as date);

但是,如果您有更多列,则需要subquery

select t.*
from table t
where t.time = (select max(t1.time)
                from table t1
                where cast(t1.time as date) = cast(t.time as date) and
                      t1.product = t.product
               );

答案 1 :(得分:2)

一种选择是在投射时使用top 1 with tiesrow_number

SELECT TOP 1 WITH TIES [Time], Product
FROM TableName
ORDER BY ROW_NUMBER() OVER(
    PARTITION BY Product, CAST([Time] AS Date) 
    ORDER BY CAST([Time] AS Time) DESC)

row_number将在每个日期的最新时间返回1。

另一种选择是使用这样的公用表表达式(或派生表):

WITH CTE AS
(
    SELECT [Time], 
           Product,
           ROW_NUMBER() OVER(
               PARTITION BY Product, CAST([Time] AS Date) 
               ORDER BY CAST([Time] AS Time) DESC) As Rn
    FROM TableName
)
SELECT [Time], Product
FROM CTE
WHERE Rn = 1

通过这种方式,您可以决定如何订购结果。

答案 2 :(得分:1)

尝试一下:

SELECT Product, MAX([Time]) FROM MyTable
GROUP BY Product, CAST([Time] AS DATE)

答案 3 :(得分:0)

您可以使用相关子查询:

select t.*
from t
where t.time = (select max(t2.time)
                from t t2
                where convert(date, t2.time) = convert(date, t.time)
               );