如何使用1个表中的PHP函数计数从2个条件(2列)中计算值(Mysql)

时间:2012-10-10 08:17:21

标签: php mysql

来自数据库

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

我只是感到困惑。

1 个答案:

答案 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

SQLFiddle Demo

如果列数未知,请使用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 Demo