I have the following table:
CREATE TABLE entries(
`id` INT UNSIGNED AUTO_INCREMENT,
`level` INT UNSIGNED,
`type` CHAR(2),
`attribute` INT UNSIGNED,
PRIMARY KEY(id)
);
From this table, I'm currently doing the same query for 3 different columns:
SELECT level, COUNT(*) FROM entries GROUP BY level;
SELECT type, COUNT(*) FROM entries GROUP BY type;
SELECT attribute, COUNT(*) FROM entries GROUP BY attribute;
I know I can use GROUP_CONCAT
to get the DISTINCT
entries for each of these in a single SQL call:
SELECT GROUP_CONCAT(DISTINCT level) AS levels, GROUP_CONCAT(DISTINCT type) AS types, GROUP_CONCAT(attribute) AS attributes FROM entries;
But can I manipulate this query to include the counts? OR is there a different way that I can get the distinct values and counts for these columns in a single call?
EDIT: here's some data to add to the table
INSERT INTO entries (level, type, attribute) VALUES (1, 'VA', 5), (1, 'CD', NULL), (NULL, 'VA', 3), (NULL, 'CD', NULL), (1, 'VA', 1);
And the sample output
LEVELS LEVEL_COUNTS TYPES TYPES_COUNTS ATTRIBUTES ATTRIBUTES_COUNTS
1 3 VA,CD 3,2 5,3,1 1,1,1
You can use the below query. The only things remaining are to add some column aliases, and to maybe add a condition to ignore rows where there is 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.