帮助编写查询的方式

时间:2010-04-28 01:58:35

标签: sql sql-server greatest-n-per-group

我需要编写一个SQL-Server查询,但我不知道如何解决。我有一个带有数据的表RealtimeData:

 Time                   |    Value
4/29/2009 12:00:00 AM   |   3672.0000
4/29/2009 12:01:00 AM   |   3645.0000
4/29/2009 12:02:00 AM   |   3677.0000
4/29/2009 12:03:00 AM   |   3634.0000
4/29/2009 12:04:00 AM   |   3676.0000      // is EOD of day "4/29/2009"
4/30/2009 12:00:00 AM   |   3671.0000
4/30/2009 12:01:00 AM   |   3643.0000
4/30/2009 12:02:00 AM   |   3672.0000
4/30/2009 12:03:00 AM   |   3634.0000
4/30/2009 12:04:00 AM   |   3632.0000
4/30/2009 12:05:00 AM   |   3672.0000      // is EOD of day "4/30/2009"
5/1/2009 12:00:00 AM    |   3673.0000
5/1/2009 12:01:00 AM    |   3642.0000
5/1/2009 12:02:00 AM    |   3672.0000
5/1/2009 12:03:00 AM    |   3634.0000
5/1/2009 12:04:00 AM    |   3635.0000      // is EOD of day "5/1/2009"

我想获得表格中存在的EOD天数。 (EOD =一天结束)。使用我的样本数据,我需要回复一个如下表格:

   Time      |    Value
4/29/2009    |  3676.0000
4/30/2009    |  3672.0000
5/1/2009     |  3635.0000

注意:我写评论以便您知道EOD在哪里。 SQL Server是2005版本。

注意:RealtimeData表中的数据非常大,超过400.000行。请帮我写优化。

请帮我解决我的问题。感谢。

4 个答案:

答案 0 :(得分:3)

WITH RankedRealTimeData AS (
  SELECT *, ROW_NUMBER() OVER (
      PARTITION BY CONVERT(VARCHAR(10), [TIME], 121) 
      ORDER BY Time DESC) AS RN
  FROM RealTimeData
)
SELECT * FROM RankedRealTimeData WHERE RN=1;

答案 1 :(得分:2)

SELECT 
    CAST(Time as DATE) EodDate, 
    (
        SELECT  TOP 1
                Value
        FROM    RealtimeData I
        WHERE   CAST(I.Time AS Date) = CAST(O.Time AS Date)
        ORDER BY    Time DESC
    ) EodValue
FROM 
    RealtimeData O
GROUP BY CAST(Time as DATE)
ORDER BY CAST(Time as DATE)

答案 2 :(得分:0)

; wcte为( 选择vTime,vValue,Row_Number()over(按转换分区(DateTime,转换(varchar(10),vTime,110))按vTime Desc命令)rno 来自@vTable )从wcte中选择vTime,vValue,其中rno = 1

答案 3 :(得分:-1)

对于不想使用指定数据库系统的人来说,使用Sql 92是最佳解决方案。

像这样:

Select A.*
From RealtimeData A
Where A.RTime >= (
    select Max(B.RTime)
    From RealtimeData B
    Where Cast((B.RTime - A.RTime) as int) <= 0
)