从mysql表转置数据

时间:2018-12-10 13:24:19

标签: php mysql

我有一个表格,其中的数据是通过指示器垂直输入的,如下例所示

^ID ^ idc1   ^ idc2 ^   idc3  ^
|1  |    7   |  11  |    5    |
|2  |    8   |  14  |   19    |
|3  |    9   |  22  |    4    |

我有一个查询,可让我将数据水平转换为水果。 但是,此查询仅给我第一行,而不是全部3

^ apples ^ Pears ^ Orange ^
|   7    |   8   |   9    | (idc1)

我想得到这个结果

^ apples ^ Pears ^ Orange ^
|    7   |   8   |    9   |   (idc1)
|    11  |   14  |   22   |   (idc2)
|    5   |   19  |    4   |   (idc3)

以下是查询:

SELECT 
    sum( if( id = 1, idc1, 0 ) ) AS Apples,  
    sum( if( id = 2, idc1, 0 ) ) AS Pears, 
    sum( if( id = 3, idc1, 0 ) ) AS Orange
FROM 
    brf_vr
WHERE  idcdate = '2018-11-27'
GROUP BY 
    idcdate;

有人有什么主意

高级THX

欢呼

1 个答案:

答案 0 :(得分:1)

尝试一下,但我不建议:

SELECT idcList,
       MAX(CASE WHEN ID = 1 THEN value END) `Apple`,
       MAX(CASE WHEN ID = 2 THEN value END) `Pears`,
       MAX(CASE WHEN ID = 3 THEN value END) `Orange`
from
  (
    SELECT ID,
           idcList,
           CASE idcList
             WHEN 'idc1' THEN idc1
             WHEN 'idc2' THEN idc2
             WHEN 'idc3' THEN idc3
             END value
    FROM mysql_test t
           CROSS JOIN
           (
             SELECT 'idc1' idcList
             UNION ALL
             SELECT 'idc2'
             UNION ALL
             SELECT 'idc3'
           ) c
  ) q
GROUP BY idcList
ORDER BY FIELD(idcList, 'idc1', 'idc2', 'idc3')

如果您可以查看架构设计