I am using MS SQL 2008. My table looks like this:
| Name | Code | Amt |
| ----- | ---- | ---- |
| April | A | 1.23 |
| Barry | A | 2.34 |
| Barry | B | 3.45 |
| Cliff | A | 4.56 |
| Cliff | B | 5.67 |
| Cliff | C | 6.78 |
I need the output to be this:
| Name | Code_A | Code_B | Code_C |
| ----- | ------ | ------ | ------ |
| April | 1.23 | NULL | NULL |
| Barry | 2.34 | 3.45 | NULL |
| Cliff | 4.56 | 5.67 | 6.78 |
The NULLs can be zero.
With a self join I am able to get Cliff, but unable to get Barry and April because i'm using something like this which only outputs if all three conditions are available.
SELECT a.Name, a.Amt Code_A, b.Amt Code_B, c.Amt Code_C
FROM Table_1 as c INNER JOIN
Table_1 AS b ON c.Name = b.Name INNER JOIN
Table_1 AS a ON b.Name = a.Name
WHERE (a.Code = 'A') AND (b.Code = 'B') AND (c.Code = 'C')
Instead of JOINs, I think a PIVOT is more appropriate here:
SELECT
Name,
[A] AS Code_A,
[B] AS Code_B,
[C] AS Code_C
FROM (
SELECT Name, Code, Amount
FROM Table_1
) t
PIVOT (
SUM(Amount)
FOR Code IN ([A], [B], [C])
) AS pvt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With