Hail to the fellow programmers and query writers,
I have this beautiful query
SELECT ID, [1] AS coL1, [15] AS coL2, [2] AS coL3, [16] AS coL4, [12] AS coL5
FROM MY_TABLE
PIVOT (sum(INT_VALUE) FOR FUND_CODE IN ([1],[2],[15],[16],[12])) AS p
--GROUP BY ID, [1] , [15] , [2] , [16] , [12]
ORDER BY ID ASC
That returns me data like this:
10001 182 NULL NULL NULL
10001 NULL 81 NULL NULL
10001 NULL NULL 182 NULL
10001 NULL NULL NULL 81
10002 165 NULL NULL NULL
10002 NULL 73 NULL NULL
10002 NULL NULL 165 NULL
10002 NULL NULL NULL 73
The 10001 and 10002 are two primary keys, and I'd like to show my data like this:
10001 182 81开发者_如何学Go 182 81
10002 165 73 165 73
I tried this commented GROUP BY to no avail. Any hints? Does it involve COALESCE?
SELECT ID ,SUM(1) AS 'col1' ,SUM(15) AS 'col2' ,SUM(2) AS 'col3' ,SUM(16) AS 'col4' ,SUM(12) AS 'col5' FROM Table GROUP BY ID
Just in CASE...
SELECT ID,
SUM(CASE WHEN FUND_CODE = 1 THEN VR_MOVIMENTACAO_QUOTA ELSE 0 END) coL1,
SUM(CASE WHEN FUND_CODE = 15 THEN VR_MOVIMENTACAO_QUOTA ELSE 0 END) coL2,
SUM(CASE WHEN FUND_CODE = 2 THEN VR_MOVIMENTACAO_QUOTA ELSE 0 END) coL3,
SUM(CASE WHEN FUND_CODE = 16 THEN VR_MOVIMENTACAO_QUOTA ELSE 0 END) coL4,
SUM(CASE WHEN FUND_CODE = 12 THEN VR_MOVIMENTACAO_QUOTA ELSE 0 END) coL5
FROM MY_TABLE
GROUP BY ID
精彩评论