用于获取非空的所有列的计数的查询;
id | Col1 | Col2 | Col3 | Col4 |
--------------------------------
1 | abc | --- | xyz | pqr |
--------------------------------
2 | def | ghi | --- | pqr |
--------------------------------
3 | --- | --- | hgy | --- |
--------------------------------
4 | --- | jko | | uyi |
--------------------------------
SELECT COUNT(*) FROM table 1 WHERE Col1!='---'
SELECT COUNT(*) FROM table 1 WHERE Col2!='---'
SELECT COUNT(*) FROM table 1 WHERE Col3!='---'
在单个查询中
如何获得结果
-----------------------
Cnt1| Cnt2 |Cnt3| Cnt4|
-----------------------
2 | 2 | 2 | 3 |
-----------------------
答案 0 :(得分:4)
有趣的是:
select count(col1) cnt1, count(col2) cnt2, count(col3) cnt3, count(col4) cnt4
from table1
答案 1 :(得分:0)
试试这个:
with data as (
select *
from ( values
(null, null, null, null),
( 1, null, null, null),
( 2, 4, null, null),
( 0, 5, 6, null)
) data(col1,col2,col3,col4)
)
select
sum(case when col1 is null then 0 else 1 end),
sum(case when col2 is null then 0 else 1 end),
sum(case when col3 is null then 0 else 1 end),
sum(case when col4 is null then 0 else 1 end)
from data
很好地产生:
----------- ----------- ----------- -----------
3 2 1 0
答案 2 :(得分:0)
看起来你有“---”值而不是空值。在这种情况下:
select count(nullif(col1,'---')) as cnt1, count(nullif(col2,'---')) as cnt2, count(nullif(col1,'---')) as cnt3, count(nullif(col1,'---')) as cnt4 from table1;