【问题标题】:join results from two sql tables连接两个 sql 表的结果
【发布时间】:2010-11-18 19:06:48
【问题描述】:

我想从按相同规则分组的两个表中获取结果,并在一次选择中连接在一起。

我有表 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

我想得到这个输出

按州分组 |按性别分组 |计数(考试成绩>0)|计数(结果>0 和结果

我试过这样的

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

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

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:
      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
    

    【讨论】:

      【解决方案2】:

      构建子选择

      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
      

      【讨论】:

      • 你能再帮忙吗,我需要计数 0 的州,没有 e.examresult 的性别按 0,1,2,3,4,5 分组
      • 从性能角度来看,相关子查询是一个糟糕的解决方案。这绝不应该是您的首选。
      • 我写这样的查询,有时长达数百行,它们通常优于其他解决方案。这可能取决于您使用的数据库。使用 Oracle 时,一条经验法则是查询看起来越差,它通常执行得越好。但是在另一个答案中的左连接可能会工作得很好,甚至可能会更好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多