2013-07-01 35 views
2

列我有一個表:總和算不算mysql中

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

謝謝你,通過@ SQL.injection回答解決問題 – Crimix

回答

1

要成功地awnser此查詢(而這正是一些awsers失敗)是你需要知道什麼是roollup一樣。如果你不想執行「手動」的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); 
+0

就像一個魅力!感謝洛特! – Crimix

0

查詢:

SELECT type, subtype, sum(type), sum(subtype) from table_name GROUP BY id 
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 | 
+------+---------+--------------+-----------+