在条件相同的表中为具有相同条件的多重查询编写单个查询 [英] Writing a single query for mutliple queries with same where condition same table

查看:74
本文介绍了在条件相同的表中为具有相同条件的多重查询编写单个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

select column1,column2,column3 from table1 where column5=0 and column6=0
select column1,column2,column3 from table1 where column5!=0 and column6!=0

这是两个SQL语句,它们从同一table1中读取数据.有没有办法编写一个返回相同数据的查询?

These are two sql statements reading data from same table1. Is there a way to write a single query that returns the same data?

我希望在单个查询中获得(column5 = 0 AND column6 = 0)和(column5!= 0 AND column6!= 0)的单独结果.

i want individual result for (column5 = 0 AND column6 = 0) and (column5 != 0 AND column6 != 0) in single query.

as example:
select column1 as c1,column2 as c2,column3 as c3 from table1 where column5=0 and  column6=0
union
select column1 as c1_,column2 as c2_,column3 as c3_ from table1 where column5!=0 and column6!=0

推荐答案

select 
sum(
 case when (column5=0 or column6=0 ) 
 then 1 else 0 end 
   ) as c1 ,

 sum(
 case when (column5=0 or column6=0 ) 
 then 1 else 0 end 
   ) as c2 ,
 sum(
 case when (column5=0 or column6=0 ) 
 then 1 else 0 end 
  ) as c3 ,

sum(
 case when (column5!=0 or column6!=0 ) 
 then 1 else 0 end 
) as c1_ ,

  sum(
 case when (column5!=0 or column6!=0 ) 
 then 1 else 0 end 
  ) as c2_ ,
 sum(
 case when (column5!=0 or column6!=0)  
 then 1 else 0 end 
   ) as c3_ ,

from table1

这篇关于在条件相同的表中为具有相同条件的多重查询编写单个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆