如何以我需要的方式获取mysql的输出如下

时间:2012-10-13 07:07:36

标签: mysql sql pivot

我有一个表,其中一列有三个值a,b和c。 表的当前快照是

表名: - tblTest

tblColumn
a
a
a
b
b
b
b
c
c

我需要将输出完全视为

A B C
3 4 2

3 个答案:

答案 0 :(得分:4)

select sum(tblColumn = 'a') as A,
    sum(tblColumn = 'b') as B,
    sum(tblColumn = 'b') as C
from tblTest

SQL Fiddle Example

答案 1 :(得分:3)

SELECT  SUM(CASE WHEN colName = 'a' THEN 1 ELSE 0 END) as A,
        SUM(CASE WHEN colName = 'b' THEN 1 ELSE 0 END) as B,
        SUM(CASE WHEN colName = 'c' THEN 1 ELSE 0 END) as C
FROM tableName

另一种技术是使用PreparedStatement,如果您有多个未知数量的值组,这是非常好的,例如,a,b,c,d,e,f,g,h,...

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(IF(tblColumn = ''',
      tblColumn,
      ''', 1, 0)) AS ',
      tblColumn 
    )
  ) INTO @sql
FROM
  Table1;
SET @sql = CONCAT('SELECT ', @sql, ' FROM Table1');

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

SQLFiddle Demo

答案 2 :(得分:2)

试试这个

select tblColumn, Count(*) from tblTest group by tblColumn