来自数据库
ID Name Department position
================================
1 A MK IT
2 B MK RD
3 C MK EN
4 D BD IT
5 E BD RD
6 F BD EN
7 G BD IT
8 H OB IT
9 I MK EN
如何编写要在表中显示的代码,如下所示
在表格中显示如下内容
position/departmet MK BD OB
===================================
IT 1 2 1
RD 1 1 0
EN 2 1 0
我只是感到困惑。
答案 0 :(得分:2)
使用CASE
,
SELECT position,
SUM(CASE WHEN Department = 'MK' THEN 1 ELSE 0 END) MK,
SUM(CASE WHEN Department = 'BD' THEN 1 ELSE 0 END) BD,
SUM(CASE WHEN Department = 'OB' THEN 1 ELSE 0 END) OB
FROM tableName
GROUP BY position
如果列数未知,请使用Prepared Statement
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(case when Department = ''',
Department,
''' then 1 ELSE 0 end) AS ',
Department
)
) INTO @sql
FROM tableName;
SET @sql = CONCAT('SELECT position, ', @sql, '
FROM tableName
GROUP BY position');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;