我在同一天有多行,我想获得过去五天当天的最新日期时间。
id username date
1 prashant 2013-10-09 05:25:46.000
2 rohit 2013-10-09 05:26:40.000
3 sam 2013-10-09 05:33:53.000
4 sohan 2013-10-09 05:26:15.000
5 mohan 2013-10-09 05:37:34.000
答案 0 :(得分:0)
SELECT id,name,MAX([date])
FROM tableName
WHERE DATEDIFF(day,[date],GETDATE()) <= 5
GROUP BY id,name
答案 1 :(得分:0)
试试这个
Select ID,
Name,
Date
From Table1
where Date
IN ( -- we are selecting the latest date for each day
SELECT MAX([date])Date
FROM Table1
GROUP BY DATEPART(dd, [date])
)
如果您只想获取过去五天的记录,请使用此
Select ID,
Name,
Date
From Table1
where Date
IN ( -- we are selecting the latest date for each day
SELECT MAX([date])Date
FROM Table1
WHERE DATEDIFF(day,[date],GETDATE()) <= 5
GROUP BY DATEPART(dd, [date])
)
答案 2 :(得分:0)
CREATE TABLE UserDate (
id INT NOT NULL IDENTITY CONSTRAINT PK_UserDate PRIMARY KEY CLUSTERED
,username nvarchar(50) NOT NULL
,dt datetime
)
INSERT INTO UserDate (username, dt)
VALUES
('usr1','2013-10-07 05:25:46.000')
,('usr2','2013-10-08 05:26:40.000')
,('usr3','2013-10-08 05:33:53.000')
,('usr4','2013-10-09 05:26:15.000')
,('usr5','2013-10-09 05:37:34.000')
,('usr6','2013-10-10 05:25:46.000')
,('usr7','2013-10-10 05:26:40.000')
,('usr8','2013-10-11 05:33:53.000')
,('usr9','2013-10-12 05:26:15.000')
,('usr10','2013-10-12 05:37:34.000')
SELECT * FROM UserDate
;With Last5 as (
SELECT
id,
username,
dt,
DENSE_RANK() OVER (ORDER BY CAST(dt as Date) DESC) OrderByDay,
ROW_NUMBER() OVER (PARTITION BY CAST(dt as Date) ORDER BY dt DESC) OrderByTime
FROM UserDate
)
SELECT *
FROM Last5
WHERE OrderByDay <= 5
and OrderByTime = 1
ORDER BY OrderByDay
GO