Это запрос для Oracle
.Измените функции, используемые в вашей соответствующей РСУБД:
WITH table_name AS
(
SELECT 'bgh567' AS user_name, 'StationA' AS station, sysdate + 1/(24*60) AS starttime, 'StationB' AS endstation, sysdate + 18/(24*60) AS endtime FROM dual UNION ALL
SELECT 'abc645'AS user_name , 'StationD' AS station, sysdate + 15/(24*60) AS starttime, 'StationX' AS endstation, sysdate + 17/(24*60) AS endtime FROM dual UNION ALL
SELECT 'yh564' AS user_name , 'StationG' AS station, sysdate + 12/(24*60) AS starttime, 'StationA' AS endstation, sysdate + 28/(24*60) AS endtime FROM dual UNION ALL
SELECT 'Yghf78'AS user_name , 'StationB' AS station, sysdate + 13/(24*60) AS starttime, 'StationC' AS endstation, sysdate + 19/(24*60) AS endtime FROM dual
)
, enter_table AS
(
SELECT
TO_CHAR(starttime, 'yyyy/mm/dd') || ' ' || TO_CHAR(starttime, 'hh24')
|| ':' || TO_CHAR(FLOOR(TO_CHAR(starttime, 'MI') / 15) * 15, 'FM00')
|| ':00' AS time_interval,
station,
COUNT(*) AS enter
FROM table_name
GROUP BY TO_CHAR(starttime, 'yyyy/mm/dd'),
TO_CHAR(starttime, 'hh24'),
FLOOR(TO_CHAR(starttime, 'MI') / 15),
station
)
, exit_table AS
(
SELECT
TO_CHAR(endtime, 'yyyy/mm/dd') || ' ' || TO_CHAR(endtime, 'hh24')
|| ':' || TO_CHAR(FLOOR(TO_CHAR(endtime, 'MI') / 15) * 15, 'FM00')
|| ':00' AS time_interval,
endstation AS station,
COUNT(*) AS exit
FROM table_name
GROUP BY TO_CHAR(endtime, 'yyyy/mm/dd'),
TO_CHAR(endtime, 'hh24'),
FLOOR(TO_CHAR(endtime, 'MI') / 15),
endstation
)
SELECT
COALESCE(e.time_interval, ex.time_interval) AS time_interval,
COALESCE(e.station, ex.station) AS station,
COALESCE(e.enter, 0) AS enter,
COALESCE(ex.exit , 0) AS exit
FROM enter_table e
FULL OUTER JOIN exit_table ex
ON e.time_interval = ex.time_interval
AND e.station = ex.station
ORDER BY 1, 2;