2014-03-13 45 views
-1

我有一個表PriceDate與兩列PriceId和PriceDate與每月3-4條目。 我想檢索每個月最後插入的PriceDate。如何從每個月選擇最後插入的DateTime?

這是我的表

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 

回答

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 
+0

感謝您的精彩支持 – Rasiuddin

+0

+1快的話 - 你不需要後DATEADD因爲它只是用於分割 –

+0

@ t-clausen.dk - 真,但是一旦我開始輸入'DATE',其餘的模式就會流出來,甚至不用考慮它。 –

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 
相關問題