我可以在同一个表的多个列上使用COUNT()获取GROUP_CONCAT吗?

时间:2014-01-31 18:48:21

标签: mysql

我有下表:

CREATE TABLE entries(
  `id` INT UNSIGNED AUTO_INCREMENT,
  `level` INT UNSIGNED,
  `type` CHAR(2),
  `attribute` INT UNSIGNED,
  PRIMARY KEY(id)
);

从这张表中,我正在对3个不同的列进行相同的查询:

SELECT level, COUNT(*) FROM entries GROUP BY level;
SELECT type, COUNT(*) FROM entries GROUP BY type;
SELECT attribute, COUNT(*) FROM entries GROUP BY attribute;

我知道我可以使用GROUP_CONCAT在一次SQL调用中获取每个DISTINCT条目:

SELECT GROUP_CONCAT(DISTINCT level) AS levels, GROUP_CONCAT(DISTINCT type) AS types, GROUP_CONCAT(attribute) AS attributes FROM entries;

但我可以操纵此查询以包含计数吗? OR是否有一种不同的方式可以在一次调用中获得这些列的不同值和计数?

编辑:这里有一些要添加到表中的数据

INSERT INTO entries (level, type, attribute) VALUES (1, 'VA', 5), (1, 'CD', NULL), (NULL, 'VA', 3), (NULL, 'CD', NULL), (1, 'VA', 1);

样本输出

LEVELS   LEVEL_COUNTS  TYPES  TYPES_COUNTS  ATTRIBUTES    ATTRIBUTES_COUNTS
1        3             VA,CD  3,2           5,3,1         1,1,1

1 个答案:

答案 0 :(得分:0)

您可以使用以下查询。剩下的唯一事情是添加一些列别名,并且可能添加一个条件来忽略存在NULL的行。

SELECT *
FROM
  (SELECT GROUP_CONCAT(lvlCount.level) as LEVELS,
          GROUP_CONCAT(lvlCount.cnt) as LEVELS_COUNTS
   FROM
     (SELECT LEVEL,
             COUNT(*) AS cnt
      FROM entries where NOT(LEVEL IS NULL)
      GROUP BY LEVEL 
      ORDER BY LEVEL DESC) AS lvlCount) AS LEVEL,

  (SELECT GROUP_CONCAT(typeCount.type) as TYPES,
          GROUP_CONCAT(typeCount.cnt) as TYPES_COUNTS
   FROM
     (SELECT TYPE,
             COUNT(*) AS cnt
      FROM entries where NOT(TYPE IS NULL)
      GROUP BY TYPE
      ORDER BY TYPE DESC) AS typeCount) AS TYPE,

  (SELECT GROUP_CONCAT(attrCount.attribute) as ATTRIBUTES,
          GROUP_CONCAT(attrCount.cnt) as ATTRIBUTES_COUNTS
   FROM
     (SELECT attribute,
             COUNT(*) AS cnt
      FROM entries where NOT(attribute IS NULL)
      GROUP BY attribute
      ORDER BY attribute DESC) AS attrCount) AS attribute;

SQLFiddle:http://sqlfiddle.com/#!2/4ea92/44