按组计算字段数据库

时间:2013-01-01 09:50:43

标签: mysql database codeigniter count

表 为了

id_order | date    | id_product | id_size | id_gender | name |
   1     |2012-1-1 |     1      |    1    |    1      | john |
   2     |2012-1-1 |     1      |    2    |    1      | mayer|
   3     |2012-1-1 |     2      |    1    |    1      | chris|

tabel产品

id_shirt |  name   |
   1     |  jeans  |
   2     |  shirt  |
   3     |  jacket |

表格大小

id_size  |  size  |
   1     |   S    |
   2     |   M    |
   3     |   L    |
   4     |   XL   |

我会在性别男性中产生这样的。

name  |  S  |  M  |  L  |  XL  |
jeans |  2  |     |     |      |
shirt |     |  1  |     |      |

请在codeigniter代码中查询。

1 个答案:

答案 0 :(得分:3)

SELECT  b.name,
        SUM(CASE WHEN c.size = 'S' THEN 1 ELSE 0 END) S,
        SUM(CASE WHEN c.size = 'M' THEN 1 ELSE 0 END) M,
        SUM(CASE WHEN c.size = 'L' THEN 1 ELSE 0 END) L,
        SUM(CASE WHEN c.size = 'XL' THEN 1 ELSE 0 END) XL
FROM    orderTB a
        INNER JOIN productTB b
            ON a.id_product = b.id_shirt
        INNER JOIN sizeTB c
            ON a.id_size = c.id_size
GROUP BY b.name

或者,如果您有未知的大小值,则更优选动态SQL ,例如

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN c.size = ''',
      size,
      ''' THEN 1 ELSE 0 END) AS ',
      size
    )
  ) INTO @sql
FROM sizeTB;

SET @sql = CONCAT('SELECT  b.name, ', @sql, ' 
                  FROM    orderTB a
                          INNER JOIN productTB b
                              ON a.id_product = b.id_shirt
                          INNER JOIN sizeTB c
                              ON a.id_size = c.id_size
                  GROUP BY b.name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;