Using this table :
| CUST | PRODUCT | QTY | SMALLEST |
-----------------------------------
| E | 1600 | 2 | 1 |
| F | 1600 | 6 | 9 |
| G | 1600 | 1 | 8 |
I want to pivot it to make it look like this:
| E | F | G |
------------------------------
| 1600 | 1600 | 1600 |
| 2 | 6 | 1 |
| 1 | 9 | 8 |
I get how to do this with one unique row. If I only have QTY or only have SMALLEST it works fine with this query for example:
Query
SELECT E, F, G
FROM (
SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT (SUM(QTY) FOR CUST IN (E,F,G)) AS pvt
Output
| E | F | G |
-------------
| 2 | 6 | 1 |
But, if I add another column to the concoction in another query, I get this mess:
Query
SELECT E, F, G
FROM (
SELECT CUST, PRODUCT, QTY, SMALLEST
FROM Product) up
PIVOT (SUM(QTY) FOR CUST IN (E,F,G)) AS pvt
Output
| E | F | G |
----------------------------
| 2 | (null) | (null) |
| (null) | (null) | 1 |
| (null) | 6 | (null) |
And it's easy to see why when I change the query:
Query
SELECT product,smallest, E, F, G
FROM (
SELECT CUST, PRODUCT, QTY, SMALLEST
FROM Product) up
PIVOT (SUM(QTY) FOR CUST IN (E,F,G)) AS pvt
Output
| PRODUCT | SMALLEST | E | F | G |
-------------------------------------------------
| 1600 | 1 | 2 | (null) | (null) |
| 1600 | 8 | (null) | (null) | 1 |
| 1600 | 9 | (null) | 6 | (null) |
The pattern becomes obvious. It's finding where there is 1600 and 1 there is one E value: 2, where there is 1600 and 8 there is one F value 6, etc.
I get the problem, but I have no clue how to fix it. Can someone aid me in my futile quest?