我有一张包含数百万条记录的表格。记录看起来像这样:
name group +--------+------+ | aaa | 1 | | bbb | 2 | | ccc | 1 | | aaa | 1 | | aaa | 2 | +--------+------+
我需要显示包含以下信息的“报告”:
当然,我不会显示所有名字的信息,所以我想只显示前100个名字(出现次数最多)。
所需输出的示例:
name count group1 group2 +------+-------+-------+-------+ | aaa | 3 | 2 | 1 | | bbb | 1 | 0 | 1 | | ccc | 1 | 1 | 0 | +------+-------+-------+-------+
到目前为止,我使用此查询计算了名称:
select * from
(select name, count(name) as count from Names s
group by name order by count desc) r
limit 100
我无法弄清楚如何计算每个组中上述查询返回的名称。
答案 0 :(得分:2)
在mysql中,您可以使用如下的简写:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL
,category INT NOT NULL
);
INSERT INTO my_table (name,category) VALUES
('aaa',1),
('bbb',2),
('ccc',1),
('aaa',1),
('aaa',2);
SELECT * FROM my_table;
+----+------+----------+
| id | name | category |
+----+------+----------+
| 1 | aaa | 1 |
| 2 | bbb | 2 |
| 3 | ccc | 1 |
| 4 | aaa | 1 |
| 5 | aaa | 2 |
+----+------+----------+
SELECT name
, COUNT(*) total
, SUM(category = 1) cat1
, SUM(category = 2) cat2
FROM my_table
GROUP
BY name;
+------+-------+------+------+
| name | total | cat1 | cat2 |
+------+-------+------+------+
| aaa | 3 | 2 | 1 |
| bbb | 1 | 0 | 1 |
| ccc | 1 | 1 | 0 |
+------+-------+------+------+
答案 1 :(得分:1)
使用Conditional Aggregate
。试试这个。
SELECT name,
Count(1) as `count`,
Count(CASE
WHEN `group` = 1 THEN 1
END) group1,
Count(CASE
WHEN `group` = 2 THEN 1
END) group2
FROM yourtable
GROUP BY name