我有一个h
包含这样数据的表(好吧,不是真的,这只是一个例子):
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
我想总结每个 q 的subj_id
结果,得到如下输出:
subj_id num1 num2 num3
1 2 1 null
2 5 2 4
3 3 null null
但相反,我得到以下信息:
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
subj_id
其中求和的行重复的次数与表中出现的次数一样多。
我的查询(postgres)如下所示:
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
左连接显然不是在这里使用的技巧,但是如何跳过重复行?
提前致谢!