48

我正在尝试从恰好存储多个状态的表中获取最后一个日期时间记录。我的桌子看起来像这样:

+---------+------------------------+-------+
|filename |Dates                   |Status |
+---------+------------------------+-------+
|abc.txt  |2012-02-14 12:04:45.397 |Open   |
|abc.txt  |2012-02-14 12:14:20.997 |Closed |
|abc.txt  |2013-02-14 12:20:59.407 |Open   |
|dfg.txt  |2012-02-14 12:14:20.997 |Closed |
|dfg.txt  |2013-02-14 12:20:59.407 |Open   |
+---------+------------------------+-------+

结果应该是

+---------+------------------------+-------+
|filename |Dates                   |Status |
+---------+------------------------+-------+
|abc.txt  |2013-02-14 12:20:59.407 |Open   |
|dfg.txt  |2013-02-14 12:20:59.407 |Open   |
+---------+------------------------+-------+
4

8 回答 8

42

如果您希望每个文件名有一行,反映特定状态并列出最近的日期,那么这就是您的朋友:

select filename ,
       status   ,
       max_date = max( dates )
from some_table t
group by filename , status
having status = '<your-desired-status-here>'

简单的!

于 2013-05-14T20:07:36.577 回答
36
SELECT * FROM table
WHERE Dates IN (SELECT max(Dates) FROM table);
于 2013-05-14T18:59:24.637 回答
21
SELECT TOP 1 * FROM foo ORDER BY Dates DESC

将返回一个最新日期的结果。

SELECT * FROM foo WHERE foo.Dates = (SELECT MAX(Dates) FROM foo)

将返回所有具有相同最大日期的结果,以毫秒为单位。

这是针对 SQL Server 的。如果您想使用日期而不是时间,我会留给您使用DATEPART函数。

于 2013-05-14T19:01:35.710 回答
7

这个工作

SELECT distinct filename
,last_value(dates)over (PARTITION BY filename ORDER BY filename)posd
,last_value(status)over (PARTITION BY filename ORDER BY filename )poss
FROM distemp.dbo.Shmy_table
于 2016-03-14T11:37:01.513 回答
4

考虑到每个文件名的 max(dates) 可能不同,我的解决方案:

select filename, dates, status
from yt a
where a.dates = (
  select max(dates)
    from yt b
    where a.filename = b.filename
)
;

http://sqlfiddle.com/#!18/fdf8d/1/0

高温高压

于 2013-05-14T19:23:54.337 回答
2

确切的语法当然取决于数据库,但类似于:

SELECT * FROM my_table WHERE (filename, Dates) IN (SELECT filename, Max(Dates) FROM my_table GROUP BY filename)

这将为您提供您所要求并在上面显示的结果。小提琴:http ://www.sqlfiddle.com/#!2/3af8a/1/0

于 2013-05-14T19:00:54.090 回答
0
select max(dates)
from yourTable
group by dates
having count(status) > 1
于 2013-05-14T18:59:16.713 回答
-3

试试这个:

SELECT filename,Dates,Status 
FROM TableName 
WHERE Dates In (SELECT MAX(Dates) FROM TableName GROUP BY filename)
于 2015-07-27T13:45:52.273 回答