I would like to get results from two tables grouped by same rules joined together in one select.
I have table 1
create table person AS
id INTEGER,
gender INTEGER,
state VARCHAR2
name VARCHAR2
surname VARCHAR2
table 2
create table sampletest as
person_id FOREIGN KEY To person.id
result INTEGER
table 3
create table examtest as
person_id FOREIGN KEY to person.id
examresult INTEGER
I would like to get this output
group by state | group by gender | count(exam开发者_如何学Cresult>0) | count(result>0 and result<4)
I tried something like this
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
but i get results that are dependent on each other. How do i get independent results into one select?
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
Build sub-selects
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
精彩评论