我有一个像这样的大答案表
person_id|question_id|answer
1|101|6
1|102|2
1|103|5
2|101|2
2|102|5
2|103|5
3|101|2
3|102|8
3|103|6
4|101|2
4|102|8
4|103|6
4|101|6
4|102|2
4|103|5
如何归还人员取决于多个问题的答案?例如,我需要回复回答的人:
6 for question 101
and 2 for question 102
and 5 for question 103
查询应返回人1和4
并考虑我需要根据10个问题进行过滤,因此我不需要在桌面上进行10次自我加入:)
答案 0 :(得分:3)
您可以使用group by
和having
:
select person_id
from t
where (question_id, answer) in ( (101, 6), (102, 2), (103, 5) )
group by person_id
having count(distinct question_id) = 3;
请注意,“3”需要与in
列表中的问题数量相匹配。
答案 1 :(得分:0)
试试这个:
SELECT DISTINCT PersonID
FROM TableName
WHERE 1 = CASE WHEN question_id = 101 AND Ans=6 THEN 1
WHEN question_id = 102 AND Ans=2 THEN 1
WHEN question_id = 103 AND Ans=5 THEN 1
END
答案 2 :(得分:0)
SELECT PersonID
FROM (
SELECT PersonID,
CASE WHEN question_id = 101 AND Ans=6 THEN 1
WHEN question_id = 102 AND Ans=2 THEN 1
WHEN question_id = 103 AND Ans=5 THEN 1
END as [count]
FROM TableName
GROUP BY PersonID,question_id,Ans
) x
WHERE x.[count]=3