将SQL数据列分组为行

时间:2018-09-21 10:21:22

标签: php mysql pdo pivot

我想将MySQL数据库的列切换为行。

对于具有这种结构的当前数据库:

id    date    category    subcategory    value
001    date1    cat1        sub1        X
002    date1    cat1        sub2        X
003    date1    cat1        sub3        X
004    date1    cat2        sub1        X
005    date1    cat3        sub1        X
006    date1    cat3        sub2        X

我想得到这个结果:

date    cat1_sub1    cat1_sub2    cat1_sub3    cat2_sub1    cat3_sub1    cat3_sub2
date1        X           X            X            X            X            X

数据库非常繁重,因此通过脚本完成此操作将花费很多时间,因此可以通过MySQL查询完成它吗?

例如,我的SQL请求是:

SELECT 
    DATE_FORMAT(FROM_UNIXTIME(data.timestamp), '%d %m %Y %h:%i:%s') as timestamp, 
    data_sub_category.designation as sub, 
    data_key.designation as dkey, 
    data_row.value as value
FROM data, data_row, data_sub_category, data_key, data_category
WHERE data.id = data_row.id_data
  AND data_category.id = data_row.id_data_category
  AND data_sub_category.id = data_row.id_data_sub_category
  AND data_key.id = data_row.id_data_key
  AND data_row.id_data_sub_category IN (1,2,3,22,1,2,3,22) 
  AND data_row.id_data_key IN (3,4,5,6,9,10,11,12,15,16,17,18,92,93,94,95,96,97,98,99,100,101,3,4,5,6,9,10,11,12,15,16,17,18,92,93,94,95,96,97,98,99,100,101) 
  AND data.timestamp BETWEEN 1536271200 AND 1536357540
ORDER BY data.timestamp

感谢您的提示

0 个答案:

没有答案