SQL Server SQL query for getting 1st and last record of each day between selected dates. Data is recorded every 10 mins

ymzxtsji  于 2023-11-16  发布在  其他
关注(0)|答案(2)|浏览(86)

MyTable

---------------------------------
time                   value
_________________________________
2023-10-13 00:08:00        15 
2023-10-13 00:18:00        13
2023-10-13 00:28:00        14
2023-10-13 00:38:00        28
|
|
|
|
2023-10-13 23:38:00        23 
2023-10-13 23:48:00        45
2023-10-13 23:58:00        25
2023-10-14 00:08:00        2
2023-10-14 00:18:00        64
|
|
2023-10-14 23:48:00        2
2023-10-14 23:58:00        6
|
|
2023-10-20 03:08:00        5 
2023-10-20 03:18:00        93
2023-10-20 03:28:00        24
2023-10-20 03:38:00        58

The desired result should look like

Date                     startVal              end val
2023-10-13                 15                     25
2023-10-14                 2                       6

Here's what I've tried:

select format(time, 'yyyy-MM-dd') as Date, min(value) as startVal, max(value) as endVal 
from MyTable 
where time between '2023-10-13' and '2023-10-20' 
group by format(time, 'yyyy-MM-dd')
vaj7vani

vaj7vani1#

One way to do it would be to use a common table expression, first_value and distinct .

First, create and populate sample table (Please save us this step in your future questions):

CREATE TABLE MyTable 
    ([time] datetime, [value] int)
;
    
INSERT INTO MyTable 
    ([time], [value])
VALUES
    ('2023-10-13 00:08:00', 15),
    ('2023-10-13 00:18:00', 13),
    ('2023-10-13 00:28:00', 14),
    ('2023-10-13 00:38:00', 28),
    ('2023-10-13 23:38:00', 23),
    ('2023-10-13 23:48:00', 45),
    ('2023-10-13 23:58:00', 25),
    ('2023-10-14 00:08:00', 2),
    ('2023-10-14 00:18:00', 64),
    ('2023-10-14 23:48:00', 2),
    ('2023-10-14 23:58:00', 6),
    ('2023-10-20 03:08:00', 5),
    ('2023-10-20 03:18:00', 93),
    ('2023-10-20 03:28:00', 24),
    ('2023-10-20 03:38:00', 58)
;

The query:

WITH CTE AS (
    SELECT CAST([time] As Date) As TheDate, 
           CAST([time] As Time) As TheTime,
           [Value]
     FROM MyTable 
)
SELECT DISTINCT TheDate, 
       FIRST_VALUE([value]) OVER(PARTITION BY TheDate ORDER BY TheTime) As FirstValue,
       FIRST_VALUE([value]) OVER(PARTITION BY TheDate ORDER BY TheTime DESC) As LastValue
FROM CTE

Results:

TheDate         FirstValue  LastValue
2023-10-13      15          25
2023-10-14      2           6
2023-10-20      5           58

You can see a live demo on db<>fiddle

aij0ehis

aij0ehis2#

See example

select convert(date,[time]) [Date]
    ,max(case when rn=1 then [value] end ) FirstValue
    ,max(case when rn=cnt then [value] end) LastValue 
FROM (
    SELECT [time],  [Value]
        ,row_number()over(partition by convert(date,[time]) order by time) rn
        ,count(*)over(partition by convert(date,[time]) ) cnt
     FROM MyTable  
) CTE
group by convert(date,[time])

There 2 Sort operations.

相关问题