从两个sql表连接结果

时间:2010-11-18 19:06:49

标签: sql postgresql

我希望从一个选择中连接在一起的两个相同规则的表中获得结果。

我有表1

create table person AS 
id INTEGER,
gender INTEGER,
state VARCHAR2
name VARCHAR2
surname VARCHAR2

表2

create table sampletest as
person_id FOREIGN KEY To person.id
result INTEGER

表3

create table examtest as 
person_id FOREIGN KEY to person.id
examresult INTEGER

我想获得此输出

按州分组|按性别分组| count(examresult> 0)| count(结果> 0,结果< 4)

我试过这样的事情

select state,gender,count(e.examresult),count(s.result) where 
p.id=s.person_id and p.id=e.person_id and 
s.result>0 and s.result<4 and 
e.examresult>0 group by state,gender

但我得到的结果相互依赖。如何将独立结果合并到一个选择中?

2 个答案:

答案 0 :(得分:3)

  SELECT state,gender,
         SUM(CASE WHEN e.examresult > 0 THEN 1 ELSE 0 END) AS EXAM_GT_ZERO,
         SUM(CASE WHEN s.result BETWEEN 0 AND 4 THEN 1 ELSE 0 END) AS SMPL_0_to_4
    FROM person p
         LEFT JOIN sampletest s
         ON p.id = s.person_id 
         LEFT JOIN examtest e
         ON p.id = e.person_id
GROUP BY state,gender

答案 1 :(得分:0)

构建子选择

select
  p.state,
  p.gender,
  sum( 
    ( select count(1) from examtest e 
      where e.personid = p.personid 
      and e.examresult > 0 ) ) as examcount,
  sum( 
    ( select count(1) from sampletest s 
      where s.personid = p.personid
      and s.result > 0 and s.result < 4) ) as samplecount
from
  person p
group by
  p.state,
  p.gender