SQL-将行作为同一表中的列

时间:2019-03-23 17:45:14

标签: mysql sql select pivot-table

我有此表,REGAL值为1-8,每个REGAL都有POLICE A-E,每个POLICE都有RADA 1-40。我想创建select,按REGAL和POLICE分组,以及许多新列1-40(按RADA值),这些列具有按WHERE CONDITION的值(因此,新列1的值为UMISTENI,其中RADA = 1)。第二张图片是我想要得到的结果。我怎样才能做到这一点?谢谢

编辑: 该脚本未返回正确的值

    SELECT REGAL, POLICE, RADA, 
CASE WHEN RADA=1 THEN UMISTENI END AS "01",
CASE WHEN RADA=2 THEN UMISTENI END AS "02",
CASE WHEN RADA=3 THEN UMISTENI END AS "03",
CASE WHEN RADA=4 THEN UMISTENI END AS "04"
FROM `ciselnik_sklad_regal_police_rada`
GROUP BY REGAL, POLICE

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

这是我的解决方案:

SELECT REGAL, POLICE, RADA, 
MAX(CASE WHEN RADA=1 THEN UMISTENI END) AS "01",
MAX(CASE WHEN RADA=2 THEN UMISTENI END) AS "02",
....
FROM `table`
GROUP BY REGAL, POLICE