2015-06-10 54 views
2

我正在使用sql语言。我试图从不同条件的表格中选择一些字段。从不同条件的同一表中选择字段

QUERY1:

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

查询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 

现在我想添加column3column4

我用下面的查询:

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 

我得到了答案。但是除了上面提到的,还有其他方法可以添加这些字段吗?有人有主意吗?

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

`

回答

2

试试这个

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

这是一个不同的选择。我没有这样想,它工作得很好。谢谢.. @SimarjeetSingh Panghlia – Rose

0
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  

哟可以在这里看到查询http://sqlfiddle.com/#!9/4321f/50

相关问题