如何从每个月中选择最后插入的DateTime?

时间:2014-03-13 08:14:10

标签: 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
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

2 个答案:

答案 0 :(得分:1)

这似乎可以解决问题:

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

答案 1 :(得分:0)

与@ Damian_The_Unbeliever类似,但使用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