I was searching a lot, but I could not find the answer. Maybe someone can give me some hints: I have a table that contains following columns and data (just an example):
+-------+------------------+----+--------+--------+
| Type | InsertDate | ID | Value1 | Value2 |
+-------+------------------+----+--------+--------+
| Data | 2019-04-29 14:30 | 01 | 2 | 1 |
| Info | 2019-04-29 14:30 | 01 | 3 | 3 |
| Data | 2019-04-29 14:42 | 01 | 5 | 5 |
| Data | 2019-04-29 14:42 | 02 | 8 | 5 |
| Info | 2019-04-28 09:30 | 02 | 1 | 7 |
| Data | 2019-04-28 12:30 | 02 | 8 | 0 |
| Data | 2019-04-28 12:10 | 02 | 3 | 1 |
+-------+------------------+----+--------+--------+
Now what I want to achive is to sum Value1 hourly for each ID where Type is Data in the configured time. I.e. from 28.04 to 29.04 I would like to have an output like:
+----+------------------+------------------+
| ID | 12:00 28-04-2019 | 14:00 29-04-2019 |
+----+------------------+------------------+
| 01 | 0 | 7 |
| 02 | 11 | 8 |
+----+------------------+------------------+
I found a lot of exaples how to sum Value1 hourly for one ID, but I need to have an output for multiple IDs.
What I have right now is the query below:
DECLARE @cols NVARCHAR(20000)
SELECT
ID,
DATEADD(hour, DATEDIFF(hour, '00:00:00', InsertDate), '00:00:00') as TruncatedToHour,
sum(Value1) as data
INTO t3
FROM table1
WHERE Type = 'Data' AND InsertDate > '2019-04-28 00:00'
GROUP BY
ID,
DATEADD(hour, DATEDIFF(hour, '00:00:00', InsertDate), '00:00:00')
SELECT @cols = LIST(DISTINCT cast(TruncatedToHour as nvarchar(1000)), ', ') FROM t3
This query returns all needed data (but not properly formated) and is dynamiclly creating column names for the needed table structure (@cols). Now I need to create needed table structure and fill it with proper data. Anyone can help?