我有一个包含id和answer列的表,如下所示:
| id | answer |
| 1 | Yes |
| 2 | No |
| 3 | Unsure |
| 1 | No |
| 1 | Unsure |
| 3 | Yes |
| 2 | Unsure |
| 4 | NULL |
| 4 | Unsure |
| 4 | No |
我希望输出的方式是,如果用户ID已经回答'是'(例如id 1),那么最终输出应该为1。 但是如果用户标识回答“否”和“空”,则输出应为“否” 此外,如果用户ID已回答“不确定”,“否”或“不确定”和“空”,则输出应为“不确定”
最终输出:
| id | answer |
| 1 | Yes |
| 2 | Unsure |
| 3 | Yes |
| 4 | Unsure |
答案 0 :(得分:0)
CASE WHEN (.Answer IS NULL OR .Answer = 'No') THEN 'NO' ELSE (.Answer) END AS 'FILTERED ANSWER'
这可以帮到你吗?
答案 1 :(得分:0)
您希望对此使用聚合和case
逻辑:
select id,
(case when sum(case when Answer = 'yes' then 1 else 0 end) > 0
then 'yes'
when sum(case when answer = 'unsure' then 1 else 0 end) > 0
then 'unsure'
else 'no' -- or perhaps max(answer)
end) as answer
from t
group by id;
如果唯一的可能性是“是”,“不”,“不确定”和NULL,那么你可以采取捷径:
select id,
(case when max(Answer) = 'yes'
then 'yes'
when max(answer) = 'unsure'
then 'unsure'
else 'no' -- or perhaps max(answer)
end) as answer
from t
group by id;