对于如下表格:
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 = "");
答案 0 :(得分: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 Server
答案 1 :(得分: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
答案 2 :(得分: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
的私人案例。