简体   繁体   中英

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

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:

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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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