I have a table h
containing data like this (OK, not really, it's just an example):
subj_id q1 q2 q3 q4 q5 q6 num
1 1 0 0 1 0 0 1
1 0 0 0 1 0 0 2
2 1 1 1 1 0 1 1
2 1 0 0 1 0 0 2
2 1 1 1 0 0 1 3
3 0 1 0 0 1 1 1
I would like to sum up the q's for each subj_id
resulting in a output like this:
subj_id num1 num2 num3
1 2 1 null
2 5 2 4
3 3 null null
but instead I get the following:
subj_id num1 num2 num3
1 2 1 null
1 2 1 null
2 5 2 4
2 5 2 4
2 5 2 4
3 3 null null
where the summed rows are repeated as many times as the subj_id
appears in the table.
My query (postgres) looks like this:
select h.subj_id, n1.sum as num1, n2.sum as num2, n3.sum as num3 from ((( h
left join (select subj_id, q1+q2+q3+q4+q5+q6 as sum from h where num=1) as n1 on h.subj_id=n1.subj_id)
left join (select subj_id, q1+q2+q3+q4+q5+q6 as sum from h where num=2) as n2 on h.subj_id=n2.subj_id)
left join (select subj_id, q1+q2+q3+q4+q5+q6 as sum from h where num=3) as n3 on h.subj_id=n3.subj_id) order by h.subj_id
Left join is obvious not the trick to use here, but what to do to skip the repeating rows?
Thanks in advance!