簡體   English   中英

多列多計數

[英]Multiple Count with Multiple column

我是sql新手。 我想數一數:

Select count(*) from table where col1= x and col2=x and Col3=x. 

我需要在所有不同的列中計數相同的值。 任何幫助將不勝感激。

您可以使用條件聚合:

Select sum(case when col1='x' then 1 else 0 end) as count_col1,
       sum(case when col2='x' then 1 else 0 end) as count_col2,
       sum(case when col3='x' then 1 else 0 end) as count_col3
  from tab;

如果要具有這些計數值的總和,請將上述查詢視為內部查詢,並使用以下方法:

 Select q.*,
        q.count_col1 + q.count_col2 + q.count_col3 whole_sum
   from     
     (
        Select sum(case when col1='x' then 1 else 0 end) as count_col1,
               sum(case when col2='x' then 1 else 0 end) as count_col2,
               sum(case when col3='x' then 1 else 0 end) as count_col3
          from tab  
      ) q

Rextester演示

暫無
暫無

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

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