使用SQL中的列名将表与值组合在一起

时间:2018-02-01 09:21:30

标签: mysql pivot-table

我有5张桌子。一个具有单独的详细信息,两个具有后两个的列名称,两个具有值。

T1: people
-----------------
|name|age|gender|
-----------------
|Alice|22 | f   |
|Bob  |33 | m   |
-----------------

T2: skillgroup names
--------------
|id | name    |
---------------
| 1 | sgn1    |
| 2 | sgn2    |
|.. |  ...    |
| 63| sgn63   |
---------------

T3: skill names
--------------
|id | name    |
---------------
|101 | sk101  |
|102 | sk102  |
|..  |  ...   |
|180 | sk180  |
---------------

T4: skillgroup person
--------------------------------
|name  | skillgroupID | value  |
--------------------------------
|Alice | 1            | 40     |
|Alice | 2            | 38     |
|...   | ..           | ..     |
|Bob   | 63           | 25     |
--------------------------------

T5: skill person
---------------------------
|name  | skillID | value  |
---------------------------
|Alice | 101     | 80     |
|Alice | 102     | 70     |
|...   | ..      | ..     |
|Bob   | 180     | 90     |
---------------------------

但是,我想得到一张这样的表:

    ------------------------------------------------------------
    |name |age|gender|sgn1|sgn2|...|sgn63|sk101|sk102|...|sk180|
    ------------------------------------------------------------
    |Alice| 22| f    | 40 | 38 |...| ... | 80  |  70 |...| ... |
    |Bob  | 33| m    | ...| ...|...|  25 | ... | ... |...| 90  |
    ------------------------------------------------------------

我该怎么做?据我所知,每个人的技能组和技能都是相同的,这意味着每个人拥有相同数量的技能组和技能。

1 个答案:

答案 0 :(得分:0)

以下mysql查询解决了您的特定问题:

SELECT
  p.name,
  p.age,
  p.gender,
  MAX(IF(skgn.name = 'sgn1', skgp.value, NULL)) AS sgn1,
  MAX(IF(skgn.name = 'sgn2', skgp.value, NULL)) AS sgn2,
  MAX(IF(skgn.name = 'sgn63', skgp.value, NULL)) AS sgn63,
  MAX(IF(skn.name = 'sk101', skp.value, NULL)) AS sk101,
  MAX(IF(skn.name = 'sk102', skp.value, NULL)) AS sk102,
  MAX(IF(skn.name = 'sk180', skp.value, NULL)) AS sk180
FROM people AS p
INNER JOIN skillgroup_person AS skgp ON p.name = skgp.name
INNER JOIN skill_person AS skp ON p.name = skp.name
INNER JOIN skillgroup_names AS skgn ON skgp.skillgroupID = skgn.id
INNER JOIN skill_names AS skn ON skp.skillID = skn.id
GROUP BY p.name, p.age, p.gender;

参见 DEMO

由于此解决方案不是动态的,如果您要将大量列转换为行数据,最好使用动态数据透视表解决方案 at this SO answer