简体   繁体   English

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

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

I have a table which contains id and answer columns which looks like: 我有一个表,其中包含id和answer列,看起来像:

| id | answer |
| 1  |  Yes   |
| 2  |   No   |
| 3  | Unsure |
| 1  |  No    |
| 1  | Unsure |
| 3  |  Yes   |
| 2  | Unsure |
| 4  | NULL   |
| 4  | Unsure |
| 4  | No     |

I want to the output in a way that if the userid has ever answered 'Yes' (like for example id 1) then the final output should have 1. But if the userid has answered "No" and "NULL" then output should be "No" Further if the userid has answered "Unsure" and "No" or "Unsure" and "Null" then output should be "Unsure" 我想以某种方式输出,如果用户id曾经回答“是”(例如id 1),那么最终输出应该为1。但是,如果用户id回答“否”和“ NULL”,则输出应该为“否”此外,如果用户ID已回答“不确定”和“否”或“不确定”和“空”,则输出应为“不确定”

Final Output: 最终输出:

| 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'

能帮到您吗?

You want to use aggregation and case logic for this: 您要为此使用聚合和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;

If the only possibilities are "yes", "no", "unsure", and NULL, then you can take a short-cut: 如果唯一的可能性是“是”,“否”,“不确定”和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