Help write a request for a requirement

I need to write a SQL-Server query, but I don't know how to solve it. I have a RealtimeData table with data:

 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"

      

I want to get the EOD data of the days that exist in a table. (EOD = end of day). With my sample data, I will need to save the table like this:

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

      

Note. I am writing a comment so you know where the EOD is. And SQL Server is version 2005.

Note: The data in the RealtimeData table is very large and exceeds 400,000 rows. Please help me write in optimization.

Please help me to solve my problem. Thanks.

+2


a source to share


4 answers


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;

      



+3


a source


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


a source


; With wcte as (Select vTime, vValue, Row_Number () over (section Convert (DateTime, Convert (varchar (10), vTime, 110)) order by vTime Desc) rno from @vTable) Select vTime, vValue from wcte where rno = 1

0


a source


Using Sql 92 is the best solution for those who don't want to use the specified DB system.

Like this:

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

      

-1


a source







All Articles