-2

从数据库

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

我只是混淆。

4

1 回答 1

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

SQLFiddle 演示

或者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;

SQLfiddle 演示

于 2012-10-10T08:20:41.127 回答