2016-09-01 3 views
0

Ich brauche die Anzahl der Felder, wo der Wert nicht null ist.Wie zähle ich Nicht-Null-Felder?

Mein Tisch

city  id_no no1 no2 no3 
    chn  A12 2158 
    chn  A13 8181 8182 8183 
    chn  A14 19138 

Ich brauche die Anzahl der Felder für no1 gesetzt zu bekommen, ..., no3

Meine Anfrage

SELECT 
    count(id_no) as total_id, 
    (count(no1) + 
    count(no2) + 
    count(no3)) as c_count 
FROM table 
    WHERE city='chn'; 

Mein Ausgang

total_id  c_count 
    3    9 

Erwartet:

total_id  c_count 
    3    5 

Ich erwarte 5 statt 9, da 5 Felder nicht null sind.

+1

'COUNT' zählt keine' NULL' Werte. Stellen Sie sicher, dass der Wert in diesen Spalten tatsächlich "NULL" und keine leere Zeichenfolge ist (ist es ein Ganzzahlfeld?) –

+0

Mögliche Duplikate von [Zählen Sie die Null-Spalten in einer Zeile in SQL] (http: // stackoverflow .com/questions/8596500/count-the-null-Spalten-in-einer-Zeile-in-sql) –

Antwort

0

oder Sie können einfach tun dies NULL oder ‚‘ zu vermeiden Daten

SELECT 
    count(id_no) as total_id, 
    (count(CASE WHEN no1 > 0 THEN no1 ELSE NULL END) + 
    count(CASE WHEN no2 > 0 THEN no2 ELSE NULL END) + 
    count(CASE WHEN no3 > 0 THEN no3 ELSE NULL END)) as c_count 
FROM table 
WHERE city='chn'; 
+0

Thk u S Bohara, ich habe die Ausgabe –

0
SELECT 
count(id_no) as total_id, 
(case when count(no1)='' or count(no1) is null then 0 else count(no1) end + 
    case when count(no2)='' or count(no2) is null then 0 else count(no2) end + 
    case when count(no3)='' or count(no3) is null then 0 else count(no3) end + 
    case when count(no4)='' or count(no4) is null then 0 else count(no4) end + 
    case when count(no5)='' or count(no5) is null then 0 else count(no5) end + 
    case when count(no6)='' or count(no6) is null then 0 else count(no6) end + 
    case when count(no7)='' or count(no7) is null then 0 else count(no7) end + 
    case when count(no8)='' or count(no8) is null then 0 else count(no8) end + 
    case when count(no9)='' or count(no9) is null then 0 else count(no9) end + 
    case when count(no10)='' or count(no10) is null then 0 else count(no10) end 
    ) as c_count 
    FROM table 
    WHERE city='chn'; 
0

Ich bin immer gleiche Ausgabe wie Sie bitte hier überprüfen möchten bieten i mein Screenshot My Output

0
SELECT count(id_no) as total_id, 
     count(CASE WHEN `nol`!="" THEN 1 END) as no1 
FROM `table` where city='chn' 

versuchen, wie diese

0
select count(distinct a.`id_no`),count(*) from 
(
    select `id_no`,`no1` as `non` from table WHERE city='chn' 
    union all 
    select `id_no`,`no2` as `non` from table WHERE city='chn' 
    union all 
    select `id_no`,`no3` as `non` from table WHERE city='chn' 
)a where a.`non` is not null 
Verwandte Themen