我有一个名为
的表Ship(Date datetime,name varchar(50),Type char(1)).
在表中发货"日期"列是datetime数据类型。我希望在Date列(Datetime数据类型)中的分钟值更改时从ship表中选择行。为此,我使用了以下查询:
;WITH x AS
(
SELECT Name, Date,Type, rn = ROW_NUMBER() OVER
(PARTITION BY Date ORDER BY Date desc)
FROM Ship
)
SELECT * FROM x WHERE rn = 1
但是期望的输出不会到来。结果是:
Date Name Type
2017-05-08 14:59:13.000 sumit A
2017-05-08 14:59:23.000 sumit B
2017-05-08 14:59:33.000 sumit A
2017-05-08 15:00:05.000 Ajay B
2017-05-08 15:00:13.000 Deep G
2017-05-08 15:01:03.000 Suri D
2017-05-08 15:01:13.000 Faiz E
在上面的输出中,当Date列的第二个值发生更改时,这些行也会出现。但是我希望在Date Column的分钟值发生变化时选择行。任何人都可以解决这个问题吗?
答案 0 :(得分:1)
您可以在datediff minute
子句
partition by
;WITH x AS
(
SELECT Name, Date,Type, rn = ROW_NUMBER() OVER
(PARTITION BY datediff(min,0,[Date]) ORDER BY Date desc)
FROM Ship
)
SELECT * FROM x WHERE rn = 1
或者它是更短的版本
SELECT TOP 1 WITH TIES
Name, Date,Type
FROM Ship
ORDER BY ROW_NUMBER() OVER (PARTITION BY datediff(min,0,[Date]) ORDER BY [date] desc)
答案 1 :(得分:0)
您可以在PARTITION BY
中添加 DATEPART ,仅在分钟部分进行更改。
;WITH x AS
(
SELECT Name, Date,Type, rn = ROW_NUMBER() OVER
(PARTITION BY DATEPART(N, Date) ORDER BY Date desc)
FROM Ship
)
SELECT * FROM x WHERE rn = 1