我有一张桌子:
id | type | subtype
如何创建查询以输出如下
type1 | subtype1 | count-subtype1 | count-type1
type1 | subtype2 | count-subtype2 | count-type1
type2 | subtype3 | count-subtype3 | count-type2
type2 | subtype4 | count-subtype4 | count-type2
即小计作为输出中的列。
没有“WITH ROLLUP”
答案 0 :(得分:1)
假设我有这种表结构:
CREATE TABLE `test` (
`id` int(11) NOT NULL auto_increment,
`type` varchar(128) default NULL,
`subtype` varchar(128) default NULL,
KEY `id` (`id`));
这个数据:
INSERT INTO `test` VALUES (1,'a','1'),(2,'a','2'),(3,'a','3'),(4,'a','4'),(5,'b','4'),
(6,'c','4'),(7,'c','1'),(8,'c','2'),(9,'c','2');
我可以这样做:
SELECT test.type, test.subtype, count(test.subtype) as countsubtype, testbytype.counttype
FROM (test)
LEFT JOIN (SELECT type, count(type) AS counttype FROM test group by type) AS testbytype ON test.type = testbytype.type
GROUP by type, subtype;
+------+---------+--------------+-----------+
| type | subtype | countsubtype | counttype |
+------+---------+--------------+-----------+
| a | 1 | 1 | 4 |
| a | 2 | 1 | 4 |
| a | 3 | 1 | 4 |
| a | 4 | 1 | 4 |
| b | 4 | 1 | 1 |
| c | 1 | 1 | 4 |
| c | 2 | 2 | 4 |
| c | 4 | 1 | 4 |
+------+---------+--------------+-----------+
答案 1 :(得分:1)
成功地查询这个查询(这是一些awsers失败的地方)是你需要知道 roollup 的作用。如果您不想执行“手动”sql汇总,还有另一个答案可以解决您的查询问题。
你需要的是两个查询,一个用于计算类型中的子类型,另一个用于计算类型。
首先计算子类型(并让我们调用此查询)。
select count(*) count_subtype, type, subtype from Foo group by type, subtype;
和另一个计算类型的查询(并让我们调用此查询)。
select count(*) count_type, type from Foo froup by type
现在你需要合并两个查询:
select t.type, s.subtype, s.count_subtype, t.conttype from
(select count(*) count_subtype, type, subtype from Foo group by type, subtype) as s
join
(select count(*) count_type, type from Foo froup by type) as t
on (t.type=s.type);
答案 2 :(得分:0)
<强>查询:强>
SELECT type, subtype, sum(type), sum(subtype) from table_name GROUP BY id