2013-05-01 43 views
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 | 
----------------------- 
+0

请清理这个问题的格式:http://stackoverflow.com/editing-help – 2013-05-01 05:48:04

回答

4

有趣的是:

select count(col1) cnt1, count(col2) cnt2, count(col3) cnt3, count(col4) cnt4 
from table1 
+0

可以请你检查的问题显然 我不需要列的计数。 我需要在哪里条件不为null的列数(null表示为---) – 2013-05-01 06:02:13

+2

@NaveenKumar阅读[手册](http://dev.mysql.com/doc/refman/5.7/en/ group-by-functions.html#function_count):“返回行中expr的**非空**值数量的计数...” – 2013-05-01 06:07:07

+0

查询结果为4 4 4 4 – 2013-05-01 06:18:38

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 
+0

选择 总和(情况下,当COL1是空值,则0,否则,1)结束时, 总和(情况下,当COL2是空值,则0,否则,1)结束时, 总和(情况下,当COL3是空值,则0,否则,1)结束时, 总和(当col4为空然后0 else 1结束) 从数据 完美地工作完成我的要求..谢谢 – 2013-05-01 06:37:43

+0

是的;其余的正在构建样本数据以进行测试。 – 2013-05-01 06:39:19

+0

这个问题被标记为[tag:mysql],它不支持'WITH'语法。 – eggyal 2013-05-01 07:48:06

0

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

select count(nullif(col1,'---')) as cnt1, count(nullif(col2,'---')) as cnt2, count(nullif(col1,'---')) as cnt3, count(nullif(col1,'---')) as cnt4 from table1;