2013-03-29 51 views
1

我有這樣的SQL:SQL:子與日期選擇

Select history.date, history.rasID, status.status 
From RAS_RASHistory as history 
inner join RAS_Status as status on History.statusID = status.statusID 
Where history.date between @startDate 
     and @endDate and history.statusID in (select value from @status) 
order by rasID, history.date desc 

當我執行它,我得到這些結果:

date     rasID status 
2011-11-17 14:15:21.693 10000 Planning 
2011-11-17 14:14:53.177 10000 New 
2011-11-16 08:39:47.770 10000 New 
2011-11-16 09:18:50.630 10001 New 
2011-11-16 11:26:23.867 10002 Planning 
2011-11-16 10:01:42.050 10002 Planning 
2011-11-16 10:00:36.527 10002 New 

我真正想要的是這樣的:

date     rasID status 
2011-11-17 14:15:21.693 10000 Planning 
2011-11-16 09:18:50.630 10001 New 
2011-11-16 11:26:23.867 10002 Planning 

但我不確定如何去得到它。我認爲可能是一種選擇,但我不太確定。有人能指引我朝着正確的方向嗎?

+0

因此,獲得最新的日期爲每個'rasID',然後獲取最新的'status' – Kermit

+0

需要更好地制定的要求。對於每個rasId條目你想要最近的狀態。那是對的嗎? – Brian

+0

是的,我想要最近的狀態。 –

回答

1
;WITH x AS 
(
    Select h.[date], h.rasID, s.[status], -- please pick better column names! 
    rn = ROW_NUMBER() OVER (PARTITION BY h.rasID ORDER BY h.[date] DESC) 
    FROM dbo.RAS_RASHistory as h -- please use dbo prefix! 
    INNER JOIN dbo.RAS_Status as s -- please use manageable aliases! 
    ON h.statusID = s.statusID 
    Where h.date between @startDate and @endDate 
    and h.statusID in (select value from @status) 
) 
SELECT [date], rasID, [status] 
FROM x 
WHERE rn = 1 
order by rasID, [date] desc; 

Also please be very careful about BETWEEN for date ranges

你也爲重新寫:

;WITH h AS 
(
    SELECT [date], rasID, statusID, 
    rn = ROW_NUMBER() OVER (PARTITION BY rasID ORDER BY [date] DESC 
    FROM dbo.RAS_RASHistory 
    WHERE [date] BETWEEN @startDate AND @endDate 
    AND statusID IN (SELECT value FROM @status) 
) 
SELECT h.[date], h.rasID, s.[status] 
    FROM h INNER JOIN dbo.RAS_Status AS s 
    ON h.statusID = s.StatusID 
    AND h.rn = 1 
ORDER BY h.rasID, h.[date] DESC; 
+0

爲什麼括號約會?只是好奇。 –

+0

@Michael因爲它是SQL Server中的一個關鍵字('date'是一種數據類型),並且如果您沒有將它放在方括號中,它將在Management Studio中呈藍色亮起。將來它可能會成爲一個保留字,除了不必要的顏色之外,它還可以幫助您在將來打樣。當然,最好的解決方案就是不要使用關鍵字作爲模糊標識符(「WHAT」的「日期」)。 –

+0

這個伎倆!謝謝! –