2014-03-26 53 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