繁体   English   中英

SQL查询以比较计数大于1的记录

[英]SQL query to compare records having count greater than 1

我有一个表,其中包含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回答“否”和“ NULL”,则输出应该为“否”此外,如果用户ID已回答“不确定”和“否”或“不确定”和“空”,则输出应为“不确定”

最终输出:

| id | answer |
| 1  | Yes    |
| 2  | Unsure |
| 3  | Yes    |
| 4  | Unsure |
CASE WHEN (.Answer IS NULL OR .Answer = 'No') THEN 'NO' ELSE (.Answer) END AS 'FILTERED ANSWER'

能帮到您吗?

您要为此使用聚合和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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM