Select fields from same table with different conditions

1.1k Views Asked by At

I am working with sql language. I tried to select out some fields from one table with different conditions.

query1:

   select PersonID,Name,count(PersonID) as column3 from Persons
   where (b1=true  or b2=true) and workingdays<100
   group by PersonID 

query 2:

  select PersonID,Name,b1+b2   as column4   from Persons
   where (b1=1 or b2=1) 
   group by PersonID) as secondset
   on baseset.PersonID=secondset.PersonID 

Now I want to add column3 and column4

I used the query below:

select 
  baseset.PersonID,
  baseset.Name,
  firstset.column3,
  secondset.column4,
  COALESCE(firstset.column3,0)+ COALESCE(secondset.column4,0) as column5
from
  (select PersonID,Namefrom Persons
   where b1=true  or b2=true)as baseset
left outer join
   (select  PersonID,Name,count(PersonID) as column3 from Persons
    where (b1=true  or b2=true) and workingdays<100
    group by PersonID
   ) as firstset
   on baseset.PersonID=firstset.PersonID
left outer join
   (select  PersonID, Name,b1+b2   as column4  from Persons
    where (b1=1 or b2=1) 
    group by PersonID
    )as secondset
   on baseset.PersonID=secondset.PersonID

I got the answer. But any other method is available to add these fields except the above mentioned ? Any one have any ideas?

SQLFIDDLE: http://sqlfiddle.com/#!9/4321f/22

`

2

There are 2 best solutions below

1
On BEST ANSWER

Try this

SqlFiddle

 select  PersonID, Name,
 case when ((b1=true  or b2=true) and workingdays<100)
 then
    count(PersonID)
 end as column3,
 case when ((b1=1 or b2=1))
 then
    b1+b2  
 end as column4,
 case when (((b1=true  or b2=true) and workingdays<100) and (b1=1 or b2=1))
 then 
    count(PersonID) + b1+b2 
 when ((b1=true  or b2=true) and workingdays<100)
 then
    count(PersonID) 
 when ((b1=1 or b2=1))
 then
     b1+b2  
 end
 as column5 
 from Persons
 where (((b1=true  or b2=true) and workingdays<100) or (b1=1 or b2=1))
 group by PersonID
0
On
select PersonID, Name, column3, column4, column3 + column4 as column5
FROM (
select baseset.PersonID, baseset.Name,
(select count(PersonID) from Persons where (b1=true  or b2=true) and     
PersonID = baseset.PersonID and workingdays<100) as column3, b1+b2 as column4
from Persons as baseset where (b1=true  or b2=true)
) as result    

Yo can see the query here http://sqlfiddle.com/#!9/4321f/50