0

获取所有非空列的计数的查询;

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

3 回答 3

4

有趣的是:

select count(col1) cnt1, count(col2) cnt2, count(col3) cnt3, count(col4) cnt4
from table1
于 2013-05-01T05:47:41.233 回答
0

看起来你有 '---' 值而不是空值。在这种情况下:

select count(nullif(col1,'---')) as cnt1, count(nullif(col2,'---')) as cnt2, count(nullif(col1,'---')) as cnt3, count(nullif(col1,'---')) as cnt4 from table1;
于 2013-05-01T06:49:22.123 回答
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
于 2013-05-01T06:14:51.040 回答