2013-05-03 72 views
0

對於表,例如:如何計數並按多列組合進行分組?

foo_table 

id | str_col | bool_col 

1 "1234"  0 
2 "3215"  0 
3 "8132"  1 
4 NULL  1 
5 ""   1 
6 ""   0 

我知道如何查詢兩個:

count(*) | bool_col 
    3   0 
    3   1 

count(*) | isnull(str_col) or str_col = "" 
    3   0 
    3   1 

,但我怎麼能得到的東西,如:

count(*) | bool_col | isnull(str_col) or str_col = "" 
    2   0   0 
    1   0   1 
    1   1   0 
    2   1   1 

在此期間,我只是個別做:

select count(*) from foo_table where bool_col and (isnull(str_col) or str_col = ""); 
select count(*) from foo_table where not bool_col and (isnull(str_col) or str_col = ""); 
select count(*) from foo_table where bool_col and not (isnull(str_col) or str_col = ""); 
select count(*) from foo_table where not bool_col and not (isnull(str_col) or str_col = ""); 

回答

1

嘗試

SELECT COUNT(*), 
     bool_col, 
     CASE WHEN str_col IS NULL OR str_col = '' THEN 1 ELSE 0 END str_col 
    FROM foo_table 
GROUP BY bool_col, 
     CASE WHEN str_col IS NULL OR str_col = '' THEN 1 ELSE 0 END 

輸出(MySQL的):

| COUNT(*) | BOOL_COL | STR_COL | 
--------------------------------- 
|  2 |  0 |  0 | 
|  1 |  0 |  1 | 
|  1 |  1 |  0 | 
|  2 |  1 |  1 | 

SQLFiddle MySQL的

SQLFiddle SQL服務器

+0

完美!我從來不知道'case',謝謝! – Kache 2013-05-03 21:25:40

+0

你當然歡迎!很高興幫助。 – peterm 2013-05-03 22:58:27

0
SELECT COUNT(CASE 
WHEN bool_col AND (isnull(str_col) or str_col = "") THEN 1 
END) as c1, 
COUNT(CASE 
WHEN not bool_col and (isnull(str_col) or str_col = "") THEN 1 
END) as c2, 
COUNT(CASE 
WHEN bool_col and not (isnull(str_col) or str_col = "") THEN 1 
END) as c3, 
COUNT(CASE 
WHEN not bool_col and not (isnull(str_col) or str_col = "") THEN 1 
END) as c4 
FROM table1 
0

在oracle中存在的,在功能構建稱爲cube

select bool_col , 
     case when str_col is null or str_col = '' then 1 else 0 end str_col , 
     count(*) 
from table1 
group by cube (bool_col , case when str_col is null or str_col = '' then 1 else 0 end) 

cube會給你所有的組合。還有rollup這是一個私人案件cube

相關問題