79277421

Date: 2024-12-13 06:54:02
Score: 0.5
Natty:
Report link

I like the elegance of Giorgos Betsos answer, but it gave me a "missing right parenthesis" error(?) which is why I refactored it to make it work and more readable for me. Feel free to fiddle with my working example here or here.

create table a_table
(
    id int,
    col1 varchar(255),
    col2 varchar(255),
    col3 varchar(255),
    col4 varchar(255)
);

insert into a_table values
    (1,'aaa','bbb','ZZZ', 'ddd'),
    (2,'aaa','XXX','ccc', 'YYY'),
    (3,'UUU','bbb','VVV', 'ddd');

WITH orig_data_query AS 
(
    SELECT id, col1, col2, col3, col4
    FROM a_table
    WHERE id IN (1,2)
),

pivot_query AS 
(
    SELECT id, val, col
    FROM orig_data_query
    UNPIVOT
    (
        val FOR col IN (col1, col2, col3, col4)
    )
)
SELECT col, MIN(VAL) AS val1, MAX(val) AS val2
FROM pivot_query
GROUP BY  col
HAVING MIN(val) <> MAX(val);
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: DeRRoN