我在Mysql中具有以下格式的数据:
name sub
----------------
a maths
a science
a history
b maths
b science
a computer
a english
c computer
c history
b history
c maths
我打算以HTML格式显示此数据:
Name maths science history computer english
a y y y y y
b y y y n n
c y n y y n
除了数据透视表方法外,如何制定我的sql查询?
答案 0 :(得分:1)
如果要动态创建列,可以使用动态数据透视。
使用GROUP_CONCAT
创建枢轴列,然后Concat SQL执行语法,动态执行它。
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'COALESCE(MAX(CASE WHEN sub = ''',
sub,
''' then ''y'' end),''n'') AS ',
sub
)
) INTO @sql
FROM T;
SET @sql = CONCAT('SELECT name, ', @sql, '
FROM T
GROUP BY name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
结果
name maths science history computer english
a y y y y y
b y y y n n
c y n y y n
答案 1 :(得分:1)
我在这里发现了类似的情况。让我简要介绍一下问题和解决方案:
问题:
将其转换为:
select * from history;
+--------+----------+-----------+
| hostid | itemname | itemvalue |
+--------+----------+-----------+
| 1 | A | 10 |
| 1 | B | 3 |
| 2 | A | 9 |
| 2 | C | 40 |
+--------+----------+-----------+
此内容:
select * from history_itemvalue_pivot;
+--------+------+------+------+
| hostid | A | B | C |
+--------+------+------+------+
| 1 | 10 | 3 | 0 |
| 2 | 9 | 0 | 40 |
+--------+------+------+------+
解决方案:
本文中,作者执行了以下步骤:
希望有帮助。
关于
答案 2 :(得分:0)
您可以在 SQL 中使用条件聚合:
SELECT name,
MAX(CASE WHEN sub = 'maths' then 'y' ELSE 'n' END) AS maths,
MAX(CASE WHEN sub = 'science' then 'y' ELSE 'n' END) AS science,
MAX(CASE WHEN sub = 'history' then 'y' ELSE 'n' END) AS history,
MAX(CASE WHEN sub = 'computer'then 'y' ELSE 'n' END) AS computer,
MAX(CASE WHEN sub = 'english' then 'y' ELSE 'n' END) AS english
FROM table t
GROUP BY name;