Надеюсь, вы можете помочь мне - сводит меня с ума:
Используя следующий код, я получаю следующий правильный вывод:
SELECT dow.day, h.hour, count(created_at)
-- FROM
-- CROSSTAB($$ SELECT h.hour, dow.day, count(created_at)::INT
FROM (values('Mon'),('Tue'),('Wed'),('Thu'),('Fri'),('Sat'),('Sun')) AS dow(day)
CROSS JOIN generate_series(0,23) as h(hour)
LEFT JOIN vehicle_state_change VSC ON to_char(VSC.state_changed_at, 'Dy')=dow.day AND extract(hour from VSC.state_changed_at)=h.hour
WHERE to_state_id = 17
AND location_id = 4
AND date_trunc('day', state_changed_at) >= '2020-02-17'
AND date_trunc('day', state_changed_at) <= '2020-02-23'
AND h.hour = 7
GROUP BY dow.day,h.hour
ORDER BY h.hour, dow.day
-- $$)
-- AS d(Hour int, "Mon" int,"Tue" int,"Wed" int,"Thu" int,"Fri" int,"Sat" int,"Sun" int);
Первые результаты
Но как только я пытаюсь запустить его в CROSSTAB, данные больше не имеют смысла, и я не могу найти решение.
SELECT *
-- dow.day, h.hour, count(created_at)
FROM
CROSSTAB($$ SELECT h.hour, dow.day, count(created_at)::INT
FROM (values('Mon'),('Tue'),('Wed'),('Thu'),('Fri'),('Sat'),('Sun')) AS dow(day)
CROSS JOIN generate_series(0,23) as h(hour)
LEFT JOIN vehicle_state_change VSC ON to_char(VSC.state_changed_at, 'Dy')=dow.day AND extract(hour from VSC.state_changed_at)=h.hour
WHERE to_state_id = 17
AND location_id = 4
AND date_trunc('day', state_changed_at) >= '2020-02-17'
AND date_trunc('day', state_changed_at) <= '2020-02-23'
AND h.hour = 7
GROUP BY dow.day,h.hour
ORDER BY h.hour, dow.day
$$)
AS d(Hour int, "Mon" int,"Tue" int,"Wed" int,"Thu" int,"Fri" int,"Sat" int,"Sun" int);
Вторые результаты