SQL简单查询

时间:2010-03-22 15:06:45

标签: sql mysql

我有下表Persons_Companies,其中显示了这些人知道的人与公司之间的关系:

PersonID  |  CompanyID

   1             1
   2             1
   2             2
   3             2
   4             2

想象一下公司1 =“Google”而公司2 =“Microsoft”,我想知道查询有以下结果:

PersonID  |  Microsoft    |    Google

   1             0                1
   2             1                1
   3             1                0
   4             1                0

直到这一刻我才有类似的东西:

select PersonID,
case when CompanyID=1 then 1 else 0
end as Google,
case when EmpresaID=2 then 1 else 0
end as Microsoft
from Persons_Companies

我的问题在于了解两家公司的人,我无法想象这个问题怎么可能。

什么是SQL查询?

4 个答案:

答案 0 :(得分:4)

select PersonID,
case when EXISTS (
   SELECT 1 
   FROM Persons_Companies pc1 
   WHERE pc.PersonID = pc1.PersonID and pc1.CompanyID = 1 ) then 1 else 0
end as Google,
case when EXISTS (
   SELECT 1 
   FROM Persons_Companies pc2
   WHERE pc.PersonID = pc2.PersonID and pc2.CompanyID = 2 ) then 1 else 0
end as Microsoft
from Persons_Companies pc

答案 1 :(得分:1)

SELECT personId, sum(case companyId when 1 then 1 else 0 end) google,
        sum(case companyId when 2 then 1 else 0 end) microsoft
from Persons_Companies
group by personId
order by personId;

答案 2 :(得分:1)

我认为这就是你想要的:http://pastie.org/881092

select
 p.person_id,
 if(ms.company_id is null,0,1) as 'microsoft',
 if(ora.company_id is null,0,1) as 'oracle',
 if(mysql.company_id is null,0,1) as 'mysql'
from
 person p
left outer join person_company ms on p.person_id = ms.person_id and ms.company_id = 1
left outer join person_company ora on p.person_id = ora.person_id and ora.company_id = 2
left outer join person_company mysql on p.person_id = mysql.person_id and  mysql.company_id = 3
order by
 p.person_id;

答案 3 :(得分:0)

这两个答案都存在问题,因为有人认为谷歌和微软将永远是桌面上唯一的公司。我相信查询应该是通用的。

我不太确定,但我认为cross tabCTE的组合效果会很好。