Question

I have a table:

id | type | subtype

how shall I create a query to output as following

type1 | subtype1 | count-subtype1 | count-type1
type1 | subtype2 | count-subtype2 | count-type1
type2 | subtype3 | count-subtype3 | count-type2
type2 | subtype4 | count-subtype4 | count-type2

Namely subtotal as a column in output.

With no "WITH ROLLUP"

Was it helpful?

Solution

To awnser this query sucessfully (and this is where some awsers fails) is that you need to know what a roollup does. If you don't want to perform a "manual" sql rollup, there is another answer around which solves your query.

what do you need is two queries, one to count the subtypes within the types and another to count the types.

first count the subtypes (and lets call this query s).

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

and another query to count the types (and lets call this query t).

select count(*) count_type, type from Foo froup by type

and now you need to merge the two queries:

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);

OTHER TIPS

Assuming that I have this structure of table:

 CREATE TABLE `test` (
  `id` int(11) NOT NULL auto_increment,
  `type` varchar(128) default NULL,
  `subtype` varchar(128) default NULL,
  KEY `id` (`id`));

And this data:

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');

I can do this:

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 |
+------+---------+--------------+-----------+

Query:

SELECT type, subtype, sum(type), sum(subtype) from table_name GROUP BY id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top