Can a MySQL query turn rows into columns?

前端 未结 3 817
醉话见心
醉话见心 2020-12-01 10:25

I have a number of tables I am trying to combine with joins but as such, the results are returned in a number of rows whereas I would like to have them generated as new colu

3条回答
  •  遥遥无期
    2020-12-01 10:36

    I'm not sure how the OP transformed from having programID and Status to how it is now, but the closest thing I would be able to get is (which does not require pivot tables):

    SELECT t1.MemberID,
        t1.FirstName,
        t1.LastName,
        concat(t2.FirstName, ' ', t2.LastName) as Spouse_Name,
        group_concat(concat(t3.FirstName, ' ', t3.LastName) ORDER BY t3.FirstName) as Children_names
    FROM member_information t1
        LEFT JOIN member_dependent_information t2 ON (t1.MemberID=t2.MemberID AND t2.Type=1)
        LEFT JOIN member_dependent_information t3 ON (t1.MemberID=t3.MemberID and t3.Type=2)
    GROUP BY MemberID;

    Which produces:

    +----------+-----------+----------+----------------+-----------------------------+
    | MemberID | FirstName | LastName | Spouse_Name    | Children_names              |
    +----------+-----------+----------+----------------+-----------------------------+
    |        1 | John      | Harris   | Amy Harris     | NULL                        |
    |        2 | Sarah     | Thompson | Bryan Thompson | Dewey Thompson,Tom Thompson |
    |        3 | Zack      | Lewis    | Minka Lewis    | Harry Lewis                 |
    +----------+-----------+----------+----------------+-----------------------------+

    and it would be "easy" with any programming language to extract that Children_names into separate columns.

提交回复
热议问题