Merging two vertical tables onto one horizontal table

亡梦爱人 提交于 2019-12-12 06:08:03

问题


Table Definitions

Table 1 (horizontal) This is a table of users

| id | name | phone |
---------------------
| 1  | Bob  | 800   |
| 2  | Phil | 800   | 

Table 2 (Vertical Table) This is a table of teams

| id | name      |
------------------
| 1  | Donkey    |
| 2  | Cat       |  

Table 3 (Vertical Table) This table is connecting the first two

| id | user_id | team_id |
--------------------------
| 1  |    1    |   1     |
| 2  |    1    |   2     |
| 3  |    2    |   1     |

My Goal

I would like to be able to query the data in such a way that i get the following back:

| id | name | phone | Donkey | Cat  |
-------------------------------------
| 1  | Bob  | 800   | 1      | 1    |
| 2  | Phil | 800   | 1      | Null |

This table would have my horizontal table data, then a combination of the other two vertical tables to create the appended columns. Where table 2 ends up being the column name headings. And the row valus are pulled from table three as a boolean.


回答1:


You're chasing a pivot table:

select u.*, 
  sum(case when t1.name = 'Donkey' then 1 else 0 end) Donkey, 
  sum(case when t1.name = 'Cat' then 1 else 0 end) Cat
  from users u
    inner join user_team ut1
      on u.id = ut1.user_id  
    inner join teams t1
      on ut1.team_id = t1.id
  group by name

demo: http://sqlfiddle.com/#!9/5fd33/7



来源:https://stackoverflow.com/questions/29501673/merging-two-vertical-tables-onto-one-horizontal-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!