SQL - 获取每个日期的最高记录

时间:2014-03-26 20:57:10

标签: sql-server

此查询中始终返回1到31个不同的日期(取决于运行月份的时间),并且可以是同一日期的倍数。
我想为查询中返回的每个日期选择前1条记录。有人能告诉我怎么做吗?

这是我的问题:

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

如果我理解,我想你想要的东西:

SELECT *
FROM dbo.EDB
WHERE ID IN 
   (SELECT MAX(ID) AS MaxID
    FROM dbo.EDB
    WHERE MONTH(currentDate) = @month
    AND YEAR(currentDate) = @year
    GROUP BY convert(varchar, currentDate, 101))
ORDER BY currentDate

答案 3 :(得分:0)

我不清楚你是如何定义顶级的,所以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