2

我需要编写一个 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

4 回答 4

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;
于 2010-04-28T02:07:00.767 回答
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)
于 2010-04-28T02:13:12.793 回答
0

;使用 wcte 作为 ( Select vTime,vValue,Row_Number() over (partition by Convert(DateTime,Convert(varchar(10),vTime,110)) order by vTime Desc) rno from @vTable )Select vTime,vValue from wcte where rno = 1

于 2010-04-30T04:23:12.283 回答
-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
)
于 2010-04-28T06:59:39.123 回答