snippetsqlMinor
How to fetch data that is not similar
Viewed 0 times
fetchdatasimilarthathownot
Problem
I have this table:
I want to fetch those records who don't have the same status records with group by user_id:
| id | user_id | status |
| a | 1 | p |
| a | 1 | p |
| a | 1 | np |
| a | 1 | pp |
| b | 2 | np |
| b | 2 | np |
| c | 3 | pp |
| c | 3 | p |
| d | 4 | p |
| d | 4 | p |I want to fetch those records who don't have the same status records with group by user_id:
| id | user_id |
| a | 1 |
| c | 3 |Solution
You can
Query:
SQL Fiddle
Output:
GROUP BY both id and user_id and only keep records HAVNG more than 1 distinct status.Query:
SELECT id
, user_id
, count(distinct status)
FROM data
GROUP BY Id, user_id
HAVING count(distinct status) > 1;SQL Fiddle
Output:
| id | user_id | count(distinct status) |
|----|---------|------------------------|
| a | 1 | 3 |
| c | 3 | 2 |Code Snippets
SELECT id
, user_id
, count(distinct status)
FROM data
GROUP BY Id, user_id
HAVING count(distinct status) > 1;| id | user_id | count(distinct status) |
|----|---------|------------------------|
| a | 1 | 3 |
| c | 3 | 2 |Context
StackExchange Database Administrators Q#131491, answer score: 3
Revisions (0)
No revisions yet.