子查询选择行作为列(pivot)

时间:2014-09-20 10:12:57

标签: mysql sql

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;

目前,上述查询的结果如下所示:

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

stopDepartures联接实际上为每个from_stop返回了多个section字段,但我只会看到第一个。如何更改stopDepartures联接以使其像透视表一样,并将每个from_stop 作为列返回? (很多列,而不是每个第一个from_stop值的1列)

1 个答案:

答案 0 :(得分:0)

如果我理解正确,这可能会做你想要的。而不是:

SELECT j.departure, stopDepartures.*

执行:

SELECT j.departure, group_concat(from_stop)

这会将所有值放在以逗号分隔的列表中。这不是每个列的单独列,但它可以满足您的需要。