2013-06-24 26 views
0

我有一個平坦的表格由數以千計的行和多於十列組成。我想爲每一行的列(非空)計數。 例如,在這裏我有平表說table A如何在平坦的表中計數數據

+=====+======+======+======+=====+======+ 
| Aid | col1 | col2 | col3 | ... |col10 | 
+=====+======+======+======+=====+======+ 
| 1 | a | b | c | ... | x | 
+-----+------+------+------+-----+------+ 
| 2 | a | b | c | ... | x | 
+-----+------+------+------+-----+------+ 
| 3 | a | b | c | ... | x | 
+-----+------+------+------+-----+------+ 

現在,我要帶數爲單查詢的所有援助都列(NOT NULL)。 例如,如果我算col1然後我需要使用 select count(*) from A where col1 is not null; 但我希望在單個查詢中的表中的每個援助的所有列計數(非空值)。 我怎麼能這樣做?

+0

你是什麼意思爲每個'Aid'做?在你的例子中它是唯一的... –

+0

是的,援助是獨一無二的..我想說的援助1值的計數是10,如果所有的列都包含一些值,並且9如果一列包含空值,其他值有一些值。 – sandeep7289

+0

好的,現在你的問題已經很清楚了 - 你想對包含每行的值的列進行計數。 –

回答

4

按照COUNT function documentation

如果指定EXPR,再算上返回行,其中EXPR不爲空的數量。

因此,您可以:

select aid, count(col1), count(col2), count(col3) 
    from t 
group by aid 
0

考慮下面的查詢

select count(a), count(b), count(c).... 
    from table_name 

select count(distinct a), count(distinct b), count(distinct c), ... 
    from table_name 

如果要統計不同值

0

馬可的答案是完美的。如果您的表格很大,並且計數的近似值正確,那麼您最好查看一下數據字典。每當你(或你的DBA)調用DBMS_STATS.GATHER_TABLE_STATS,它收集準確的計數,並將其存儲在一個觀點:

SELECT column_name, num_nulls 
    FROM user_tab_columns 
WHERE table_name='A'; 
0

如果你使用11g中,您可以使用unpivot,然後通過援助與一組數:

select aid,count(*) 
from tablea 
unpivot 
(
    vals for col_name in (col1, col2, col3, ..., col10) 
) 
group by aid 
order by aid 

Here is a sqlfiddle demo

相關問題