使用相同的列相同的表为多个where条件写一个查询

时间:2011-10-22 09:33:07

标签: mysql sql join conditional-statements

在我的表中,提交的文件之一是msg。基于此提交的两个条件。条件是

where  msg  like '%fatal%' or msg like '%exception%' or msg like '%fopen%'

then Select telco ,
Sum(Case when a= '1' then 1 else 0 end) as a, 
Sum(Case when b= '2' then 1 else 0 end) as b, 
Sum(Case when c= '3' then 1 else 0 end) as c,


where  msg not like '%fatal%' or msg not like '%exception%' or msg not like   '%fopen%'
then Select telco ,
Sum(Case when a= '1' then 1 else 0 end) as a_e, 
Sum(Case when b= '2' then 1 else 0 end) as b_e, 
Sum(Case when c= '3' then 1 else 0 end) as c_e,

From temp_inbox  group by t

这里是a,b,c列名称

我想写一个查询上面的要求。如果我写两个查询基于两个条件然后我得到结果但我想写单个查询并以下列方式显示我的结果:

a   b   c   a_e   b_e   c_e

5   6   7    10    4     10
1   2   7     45   20    2

示例数据:

         a  b   c  msg

         1  0   0  fatalerror

         0  0   3   successed
         1  0   0   exception
         0  2   0   successful

2 个答案:

答案 0 :(得分:1)

select telco, 
sum(
     case when (msg  like '%fatal%' or out_msg like '%exception%' or out_msg like '%fopen%') and a = '1' 
     then 1 else 0 end 
) as a,
sum(
     case when (msg  like '%fatal%' or out_msg like '%exception%' or out_msg like '%fopen%') and a = '2' 
     then 1 else 0 end 
) as b,
sum(
     case when (msg  like '%fatal%' or out_msg like '%exception%' or out_msg like '%fopen%') and a = '3' 
     then 1 else 0 end 
) as c,
 sum(
     case when (msg not like '%fatal%' or out_msg not like '%exception%' or out_msg not like '%fopen%') and a = '1' 
     then 1 else 0 end 
) as a_e,
sum(
     case when (msg not like '%fatal%' or out_msg not like '%exception%' or out_msg not like '%fopen%') and a = '2' 
     then 1 else 0 end 
) as b_e,
sum(
     case when (msg not like '%fatal%' or out_msg not like '%exception%' or out_msg not like '%fopen%') and a = '3' 
     then 1 else 0 end 
) as c_e

From temp_inbox  group by t

或者您可以在输入时使用嵌套大小写

答案 1 :(得分:0)

您可以使用UNION语句连接具有相同列数的两个查询:

我不确定你想做什么,但是你提到的表中的UNION声明看起来像这样:

select sum(a), message from telco where message like '%fatal%'
UNION
select sum(a), message from telco where message not like '%fatal%'
相关问题