2

我有一张桌子:

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

即小计作为输出中的一列。

没有“与汇总”

4

3 回答 3

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 |
+------+---------+--------------+-----------+
于 2013-07-01T07:21:58.010 回答
1

要成功地执行此查询(这就是某些 awsers 失败的地方),您需要知道汇总的作用。如果您不想执行“手动”sql 汇总,还有另一个答案可以解决您的查询。

您需要的是两个查询,一个用于计算类型中的子类型,另一个用于计算类型。

首先计算子类型(并让我们调用这个查询)。

select count(*) count_subtype, type, subtype from Foo group by type, subtype;

和另一个用于计算类型的查询(并让我们将此查询称为 t)。

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);
于 2013-07-01T07:46:28.007 回答
0

询问:

SELECT type, subtype, sum(type), sum(subtype) from table_name GROUP BY id
于 2013-07-01T07:12:26.830 回答