2016-08-30 54 views
0
My table like 
    --------------- 
     trtm  t_date   id_no certno1 certno2 certno3 certno4 certno5 certno6 certno7 certno8 certno9 certno10 
     TM  15/02/2002  A12  2158 
     TM  15/02/2010  A13  8181  8182  8183  8184  8185  8186  8187  8188  8189  8190 
     TM  15/02/2010  A14  19138 
     ------------------- 

我需要id_no上和certno的数量从1到10如何使用SQL获得多列的计数

my query is 
    ---------- 
    select count(id_no) as total_id,count(CONCAT(certno1, certno2, certno3,certno4,certno5,certno6,certno7,certno8,certno9,certno10)) as certificate from table where trtm='TM' 
    ---------- 
    my output is: 
    --------- 
    total_id  certificate 
     3    3 
    ------------------------- 

,但我需要证明的计数其中的值有3,但我需要的是12

------------ 
    output needs: 
    ----------- 
    total_id  certificate 
     3    12 
    ------------- 

我只得到total_id和certificate.so计数,请帮助我,如果有人知道。

+0

见正常化 – Strawberry

回答

2

假设“空” certX字段是空,你需要这样的事:

SELECT (cert1 is not null) + (cert2 is not null) + ... (cert10 is not null) 

每个is not null测试将返回一个true/false,这会被MySQL类型强制转换为整数,转换为基本的1+1+0+1+....类型加法运算。

+0

谢谢你马克乙 –

1

分别计数,然后SUM它:

SELECT 
    count(id_no) as total_id, 
    (count(certno1) + 
     count(certno2) + 
     count(certno3) + 
     count(certno4) + 
     count(certno5) + 
     count(certno6) + 
     count(certno7) + 
     count(certno8) + 
     count(certno9) + 
     count(certno10)) as certificate 
FROM table 
WHERE trtm='TM'; 
+1

我所知,'sum'需要一个argument..you被传递多个参数在这里..使用'+'改为添加计数。 –

+0

谢谢Shaharyar –

+0

@ sukumarK.G接受答案,如果它帮助你解决问题。 – Shaharyar