I have a database which looks like that:
ID gesamtzaehler gutzaehler timestamp
1 7119529 7007905 2023-03-01 14:09:15.043
2 7119553 7007929 2023-03-01 14:10:15.013
3 7119577 7007953 2023-03-01 14:11:15.043
4 7119601 7007977 2023-03-01 14:12:15.030
5 7119625 7008001 2023-03-01 14:13:15.047
6 7119649 7008025 2023-03-01 14:14:15.010
7 7119673 7008049 2023-03-01 14:15:15.010
8 7119697 7008073 2023-03-01 14:16:15.027
9 7119721 7008097 2023-03-01 14:17:15.027
10 7119731 7008107 2023-03-01 14:18:15.043
11 7119731 7008107 2023-03-01 14:19:15.057
12 7119731 7008107 2023-03-01 14:20:15.040
13 7119731 7008107 2023-03-01 14:21:15.010
and want to get the hourly greatest difference between Gesamtzaehler and Gutzaehler. Everything works fine like that:
SELECT MAX(gesamtzaehler - gutzaehler) - MIN(gesamtzaehler - gutzaehler) AS Ausschuss, CAST(DATEPART(Hour, timestamp) AS varchar) + ':00' AS Hour
FROM dbo.Zaehler
WHERE (timestamp >= DATEADD(hour, - 24, GETDATE()))
GROUP BY DATEPART(hh, timestamp)
The Answer of the Statement is this:
Ausschuss Hour
12 0:00
13 23:00
6 15:00
14 3:00
3 6:00
11 21:00
63 7:00
4 1:00
14 18:00
19 4:00
25 19:00
7 5:00
0 22:00
5 16:00
15 2:00
29 17:00
4 20:00
2 14:00
And here is my problem. For my visualization I need the Hour column to be sorted. As for example a timestamp can be sorted. If it is 7 ' O-Clock the sorting mechanism should bring the result (like order by timestamp 8-24-7)... it will in this example always sort from 0 - 24.
Thank you for your help.
2条答案
按热度按时间suzh9iv81#
If we take a slightly modified version of your example data (it's really helpful if you provide this as reproducible DDL/DML when asking questions):
Then we can do something like this:
What are we doing here? First, we build out a CTE to give us all the hours from our start time (24 hours ago) until now. This let's us have a row for each hour, even though it may not be present in the data. Then we LEFT OUTER JOIN to our aggregated data to get the values for that hour. In the sub query, we're aggregating the data up in a similar way to your example, but we're preserving the data type of DATETIME.
tvokkenx2#
if you are using SQL-Server 2022, you can directly order by datetrunc() function.
If you are using an older version of SQL-Server, you can use the following code( dateadd() and datediff() ) to truncate timestamps to hour and then order by truncated timestamps.
Here is the quey: