简体   繁体   中英

Sub-query select rows as columns (pivot)

SELECT j.departure, stopDepartures.*
FROM journey j
JOIN journey_day ON journey_day.journey = j.id
JOIN service ON service.id = j.service
JOIN pattern ON j.pattern = pattern.id
JOIN (
    SELECT section, pl.from_stop
    FROM pattern_link pl
    WHERE pl.section = section
) stopDepartures ON stopDepartures.section = pattern.section
WHERE service.id = "59924-44-X4-B-y10-2" AND journey_day.day = 1 AND pattern.direction = "outbound" AND DATE(NOW()) BETWEEN service.date_start AND service.date_end
GROUP BY j.id
ORDER BY departure ASC;

Currently, results for the above query will look something like:

`departure` | `section` | `from_stop`
    07:00    some_var_id  some_var_id

But the stopDepartures join is actually returning many from_stop fields for each section , but I will only ever see the first one. How can I change the stopDepartures join so that it acts like a pivot table, and returns each from_stop as a column ? (Lots of columns, rather than 1 column for each first from_stop value)

If I understand correctly, this may do what you want. Instead of:

SELECT j.departure, stopDepartures.*

Do:

SELECT j.departure, group_concat(from_stop)

This puts all the values in a comma-delimited list. This is not a separate column for each one, but it may do what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM