I have 2 tables.
The dummy
table:
and the down_event
table:
availability_time
in the dummy
table ranges from 00:00:00 to 23:00:00. Every down_duration_sec
in the down_event
table shall be subtracted from duration_sec
in the corresponding row of the dummy
table. An event occurring at down_time
03:59:59 only applies to the row with availability_time
03:00:00 in the dummy
table.
The example above only shows rows for 2020-02-25, but there can be many dates for the same terminal_id
.
To be clear, assuming these rows in table dummy
:
terminal_id availability_date availability_time duration_sec
___________ _________________ _________________ ____________
02262261 2020-02-25 00:00:00 3600
02262261 2020-02-25 01:00:00 3600
02262261 2020-02-25 02:00:00 3600
02262261 2020-02-25 03:00:00 3600
For an event occurring on the date 2020-02-25 at the time 1:43:23 with a down_duration_sec
of 10 seconds, the dummy
table shall be updated to:
terminal_id availability_date availability_time duration_sec
___________ _________________ _________________ ____________
02262261 2020-02-25 00:00:00 3600
02262261 2020-02-25 01:00:00 3590
02262261 2020-02-25 02:00:00 3600
02262261 2020-02-25 03:00:00 3600
So far this is my query code:
UPDATE dashboard.dummy
SET duration_sec = 3600 - t.down_duration_sec
FROM (
SELECT down_duration_sec
FROM dashboard.down_event
WHERE terminal_id IN (SELECT terminal_id FROM dashboard.dummy)
GROUP BY down_duration_sec
) t
WHERE t.terminal_id = dashboard.dummy.terminal_id
AND availability_date IN (
SELECT down_date
FROM dashboard.down_event
WHERE down_date IN ( SELECT availability_date FROM dashboard.dummy)
)
This query works and was able to populate the terminal_id, availability_date and availability_time.
But once I add this code to subtract the duration_sec
:
AND availability_time IN(
SELECT terminal_id, down_time
FROM dashboard.down_event
WHERE down_time between
(
SELECT terminal_id, availability_time
FROM dashboard.dummy
WHERE terminal_id IN (SELECT terminal_id FROM dashboard.down_event)
GROUP BY terminal_id, availability_time
)
AND
(
SELECT availability_time + interval '1 hour'
FROM dashboard.dummy
WHERE terminal_id IN (SELECT terminal_id FROM dashboard.down_event)
GROUP BY availability_time
)
)
.. I get the error:
subquery must return only one column
How do I get the subtraction right?