complex dynamic SQL query, joining on self

527 Views Asked by At

I'm looking to tackle a difficult SQL query. I'd appreciate some input on how to achieve this relatively complex SQL query on a table.

I currently have a table as follows:

caseId scanId attribute
-----------------------
  1      2       A
  1      4       A
  2      3       B
  3     NULL    NULL

I want to be able to achieve this table:

caseId scanId1 scanId2 attribute1 attribute2 count
--------------------------------------------------
  1       2       4        A          A        2
  2       3      NULL      B        NULL       1
  3     NUL      NULL     NULL      NULL       0

I know this involves joining the table on itself, however I can't come up with how to dynamically make the number of columns (scanId1, scanId2, etc.) required, which depends on the number of unique caseId tuples.

Any tips on how I can get this to work?

Thanks in advance!

1

There are 1 best solutions below

0
On

You can try this. It works

SELECT
    caseId,
    MAX(CASE WHEN scanId IN (2,3) THEN scanId ELSE NULL END) AS scanId1,
    MAX(CASE WHEN scanId=4 THEN scanId ELSE NULL END ) AS scanId2,
    MAX(CASE WHEN attribute =('A', 'B')THEN attribute ELSE NULL END) AS attribute1,
    MAX(CASE WHEN attribute IN ('A') THEN attribute ELSE NULL END ) AS attribute2,    
    count(scanId) AS counts    
FROM 
    GGG    
GROUP BY
    caseId