There is a column representing 24 hours. Data comes in every 15 minutes. For example, at 10:15, the value is entered in the DateTime column of the 10H column. But… The client wants to set the standard for the day at 6:30 a.m. and set it to 6:30 the next day. If you look at the column below, should sum the value from column 6h.. Is there any way?
DateTime 0H 1H ..6H....7H...8H..9H..10H..~23H 2020 11 10 00:00:00 979 958 2020 11 10 00:15:00 987 954 2020 11 10 00:30:00 987 958 2020 11 10 00:45:00 960 956 2020 11 11 00:00:00 0 0 2020 11 11 00:15:00 0 0 2020 11 11 00:30:00 0 0 2020 11 11 00:45:00 0 0 2020 11 12 00:00:00 995 995 2020 11 12 00:15:00 991 993 2020 11 12 00:30:00 1000 993 2020 11 12 00:45:00 993 996
I want value 2020-11-15 06:30 ~ 2020-11-16 06:30 values sum
Advertisement
Answer
Consider breaking hour blocks into separate SELECT
segments that add corresponding hour columns. Then, bind all parts together by UNION ALL
. Finally, aggregate all hour blocks for final SUM
.
Below sums all values between 2020-11-15 06:30 - 2020-11-16 06:30
(not including upper limit). Be sure to fill in the abbreviated ...
for needed columns:
SELECT SUM(sub.HoursTotal) AS DayTotal FROM ( -- PARTIAL HOUR - 6:30 AM - 6:45 AM SELECT [6h] AS HoursTotal FROM myTable WHERE logdatetime BETWEEN '2020 11-15 00:30:00' AND '2020 11-15 00:45:00' UNION ALL -- FULL HOURS - 7:00 AM - 23:00 PM SELECT [7h] + [8h] + ... + [23h] AS HoursTotal FROM myTable WHERE logdatetime BETWEEN '2020 11-15 00:00:00' AND '2020 11-15 00:45:00' UNION ALL -- FULL HOURS - 12:00 AM - 5:00 AM SELECT [0h] + [1h] + ... + [5h] AS HoursTotal FROM myTable WHERE logdatetime BETWEEN '2020 11-16 00:00:00' AND '2020 11-16 00:45:00' UNION ALL -- PARTIAL HOUR - 6:00 AM - 6:15 AM SELECT [6h] AS HoursTotal FROM myTable WHERE logdatetime BETWEEN '2020 11-16 00:00:00' AND '2020 11-16 00:15:00' ) sub
Of course, ideally your table maintains a normalized structure of long format with two columns for datetime and value. Then, querying is much easier:
logDateTimewithHour Value 2020 11-15 00:00:00 ### 2020 11-15 00:15:00 ### 2020 11-15 00:30:00 ### 2020 11-15 00:45:00 ### 2020 11-15 01:00:00 ### 2020 11-15 01:15:00 ### 2020 11-15 01:30:00 ### 2020 11-15 01:45:00 ### ... ... 2020 11-16 22:00:00 ### 2020 11-16 22:15:00 ### 2020 11-16 22:30:00 ### 2020 11-16 22:45:00 ### 2020 11-16 23:00:00 ### 2020 11-16 23:15:00 ### 2020 11-16 23:30:00 ### 2020 11-16 23:45:00 ###
SELECT SUM(Value) AS DayTotal FROM myLongTable WHERE logDateTimewithHour BETWEEN '2020 11-15 06:30:00' AND '2020 11-16 06:15:00'