Got this question for a while and wondering if there is any faster query.
I have a table with multiple entries per ID, and would like to list all columns with different values for the same ID.
| ID | Brand | Type |
|---|---|---|
| 1 | Honda | Coupe |
| 1 | Jeep | SUV |
| 2 | Ford | Sedan |
| 2 | Ford | Crossover |
Example for above table:
Rows with ID = 1 have different Brand and Type values, so I want one result row for each column.
For ID = 2 there is only one brand, but multiple types, so only one result row for type.
The desired result would be like this.
| ID | Difference |
|---|---|
| 1 | Brand |
| 1 | Type |
| 2 | Type |
I solved it with below query checking each column with one SELECT statement and then UNION it all:
SELECT ID, 'Brand' AS Discrepancy
FROM table
GROUP BY ID
HAVING COUNT(DISTINCT Brand) > 1
UNION
SELECT ID,'Type' AS Discrepancy
FROM table
GROUP BY ID
HAVING COUNT(DISTINCT Type) > 1;
Is there any faster query or optimization?