Mysql 多列多计数
我是sql新手。我想数一数,比如:Mysql 多列多计数,mysql,sql,Mysql,Sql,我是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_col
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
您可以使用条件聚合:
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
谢谢您的回复。我也可以计算所有列值的总和吗?@AyesaJannat欢迎,是的,当然可以,这取决于数据的语法。如何计算3列的总数?哇!!非常感谢。更简单的是求和条件,而不将
大小写
:sum(col1='x')作为count\u col1
,谢谢您的回复。我也可以计算所有列值的总和吗?@AyesaJannat欢迎,是的,当然可以,这取决于数据的语法。如何计算3列的总数?哇!!非常感谢。更简单的方法是将条件求和,而不将大小写
:sum(col1='x')作为count\u col1
,