How do I turn the top dataset into the bottom dataset, so that I can add it to another joined table?
I was trying Cross joins and Pivots but nothing seemed to work.
How do I turn the top dataset into the bottom dataset, so that I can add it to another joined table?
I was trying Cross joins and Pivots but nothing seemed to work.
Please search before asking. Simple pivot examples are already on this site numerous times. Here's another simple example using PIVOT:
CREATE TABLE animals (
ID int
, ChildID int
, [Name] nvarchar(50)
, Age int
);
INSERT INTO animals (ID, ChildID, [Name], Age)
VALUES (1, 654, 'Cat', 1)
, (2, 654, 'Dog', 2)
, (5, 655, 'Cat', 4)
, (6, 655, 'Dog', 3)
;
SELECT ChildID
, PivotTable.[Cat]
, PivotTable.[Dog]
FROM (
SELECT ChildID, [Name], Age
From animals
) as sourceTable
PIVOT (
SUM([Age])
FOR [Name] IN ([Cat],[Dog])
) as pivotTable
ORDER BY ChildID
;
ChildID | Cat | Dog |
---|---|---|
654 | 1 | 2 |
655 | 4 | 3 |