簡體   English   中英

如何使用SQL獲取多列計數

[英]How to get count of multiple column using sql

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

我需要從1到10計數id_no和certno

   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中的計數,如果有人知道,請幫助我。

假設“空” certX字段為空,則需要這樣的操作:

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

每個is not null測試將返回一個布爾值true / false,這將由mysql類型轉換為整數,並轉換為基本的1+1+0+1+.... -type加法運算。

單獨計數,然后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';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM