2014-03-26 75 views
0

在此查詢中返回的總是有1到31個不同日期(具體取決於它在運行月份中的何時),並且可能有多個相同日期。
我想爲查詢中返回的每個日期選擇前1條記錄。有人可以告訴我如何做到這一點?SQL - 獲取每個日期的最高記錄

這裏是我的查詢:

SELECT  
currentDate 
,month(currentDate) month 
,DATENAME(month, currentDate) as 'MonthName' 
,DATEPART(wk,currentDate) week 
,LEFT(CAST(DATEPART(YEAR,currentDate) AS CHAR),4) + 
RIGHT('0' + CAST(datepart (week,currentDate) AS VARCHAR(2)),2) AS Yearweek 
,RTMCode 
,RTM 
,CPCode 
,CP 
,CDCode 
,CD 
,Branded 
,RV 
,Holiday 
FROM dbo.EDB 
+1

定義「top」?這是那一天的第一個入口嗎? – Snake

回答

1

使用CROSS APPLY。假設CurrentDate是DATE列,這裏是一個例子。如果currentdate是datetime,則必須將ORDER BY更改爲ID或CurrentDate。

SELECT t2.currentDate 
,month(t2.currentDate) month 
,DATENAME(month, t2.currentDate) as 'MonthName' 
,DATEPART(wk,t2.currentDate) week 
,LEFT(CAST(DATEPART(YEAR,t2.currentDate) AS CHAR),4) + 
RIGHT('0' + CAST(datepart (week,t2.currentDate) AS VARCHAR(2)),2) AS Yearweek 
,RTMCode 
,RTM 
,CPCode 
,CP 
,CDCode 
,CD 
,Branded 
,RV 
,Holiday 
FROM 
(SELECT currentDate 
FROM dbo.EDB e 
GROUP BY currentDate)t 
CROSS APPLY (SELECT TOP 1 * FROM dbo.EDB i1 
      WHERE i1.currentDate = t.CurrentDate 
      ORDER BY i1.currentDate DESC)t2 
+0

好吧,你上面的東西似乎工作得很好,沒有我改變任何東西。 「currentDate」列是日期。柱。 – Kevin

0

我不知道你想要什麼。這是你想要的東西 -

樣品表 -

id dates 
2 2014-03-01 
1 2014-03-01 
3 2014-03-01 
5 2014-03-02 
6 2014-03-02 

查詢 -

select MAX(id) as TopZ, dates 
from datings 
group by dates 
order by dates asc 

結果 -

TopZ dates 
3  2014-03-01 
6  2014-03-02 
0

如果我的理解,我覺得你想要的東西,如:

0

我不清楚你是如何定義top的,所以max可能不夠靈活。我還假設你在桌子上有某種主鍵。

WITH cte AS (
    SELECT pk 
     ,ROW_NUMBER OVER(PARTION BY currentDate ORDER BY [whatever]) rn 
    FROM EDB 
) 
SELECT a.* 
    FROM EDB a 
     INNER JOIN 
     cte b ON a.pk = b.pk 
WHERE b.rn = 1