Sql server 如何从每个月选择最后插入的日期时间?
我有一个表PriceDate,它有两列PriceId和PriceDate,每个月有3-4个条目。 我想检索每个月最后插入的PriceDate 这是我的桌子Sql server 如何从每个月选择最后插入的日期时间?,sql-server,tsql,Sql Server,Tsql,我有一个表PriceDate,它有两列PriceId和PriceDate,每个月有3-4个条目。 我想检索每个月最后插入的PriceDate 这是我的桌子 PriceDate PriceId 2012-01-07 00:00:00.000 1 2012-01-14 00:00:00.000 2 2012-01-21 00:00:00.000 3 2012-01-28 00:00:00.000 4 2012-02-04 00:00:00.000 5 20
PriceDate PriceId
2012-01-07 00:00:00.000 1
2012-01-14 00:00:00.000 2
2012-01-21 00:00:00.000 3
2012-01-28 00:00:00.000 4
2012-02-04 00:00:00.000 5
2012-02-11 00:00:00.000 6
2012-02-18 00:00:00.000 7
2012-02-25 00:00:00.000 8
我需要这个输出
PriceDate DateFormat PriceId
2012-01-28 00:00:00.000 Jan 2012 4
2012-02-25 00:00:00.000 Feb 2012 8
这似乎起到了作用:
declare @t table (PriceDate datetime not null, PriceId int not null)
insert into @t(PriceDate,PriceId) values
('2012-01-07T00:00:00.000',1),
('2012-01-14T00:00:00.000',2),
('2012-01-21T00:00:00.000',3),
('2012-01-28T00:00:00.000',4),
('2012-02-04T00:00:00.000',5),
('2012-02-11T00:00:00.000',6),
('2012-02-18T00:00:00.000',7),
('2012-02-25T00:00:00.000',8)
;With Numbered as (
select *,
ROW_NUMBER() OVER (
PARTITION BY DATEADD(month,DATEDIFF(month,0,PriceDate),0)
ORDER BY PriceDate desc) as rn
from @t
)
select PriceDate,
RIGHT(CONVERT(varchar(20),PriceDate,106),8) [Dateformat],
PriceId
from Numbered where rn=1
DATEADD
/DATEDIFF
技巧基本上是将每个日期四舍五入到各自月份的开始
结果:
PriceDate Dateformat PriceId
----------------------- -------- -----------
2012-01-28 00:00:00.000 Jan 2012 4
2012-02-25 00:00:00.000 Feb 2012 8
与不信者的@Damian_类似,但使用
YEAR()
和Month()
函数
;WITH DateOrdered
AS
(
SELECT PriceDate, PriceId,
ROW_NUMBER() OVER (
PARTITION BY YEAR(PriceDate), MONTH(PriceDate)
ORDER BY PriceDate DESC) As Num
from PriceDate
)
SELECT PriceDate, RIGHT(CONVERT(varchar(20),PriceDate,106),8) [Dateformat], PriceId
FROM DateOrdered
WHERE Num = 1
+1快速评论-您不需要在datediff之后添加dateadd,因为它只是用于partitioning@t-clausen.dk-是的,但是一旦我开始键入
DATE
,模式的其余部分就流出来了,我甚至都没有想到它。