Reputation: 61
How can I write a query in SQL Server that returns a column for each variable of each unique ID? Below is a simplified example of what I am trying to accomplish. Would you be able to point me in the right direction?
Table_Exists
ID | LOCATION | STATUS
__________________________________
001 | top | 3
001 | mid | 1
001 | bot | 4
002 | top | 2
002 | mid | 2
002 | bot | 1
003 | top | 1
003 | mid | 4
003 | bot | 2
Here is a simplified example of what I am trying, obviously without success. The code below returns an error message for incorrect syntax around '=':
SELECT
ID,
LOCATION = top AS Top,
LOCATION = mid AS Middle,
LOCATION = bot AS Bottom
FROM
Table_Exists
I trying to build:
Table_Desired
ID | Top | Middle | Bottom
__________________________
001| 3 | 1 | 4
002| 4 | 2 | 2
003| 1 | 4 | 2
Upvotes: 2
Views: 112
Reputation: 175646
You can use self join (as long as your LOCATION
is NOT NULL
and it contains all top/mid/bot
values):
SELECT t1.ID, t1.Status AS Top, t2.Status AS Middle, t3.Status AS Bottom
FROM Table_Exists t1
JOIN Table_Exists t2
ON t1.ID = t2.ID
AND t1.LOCATION = 'top'
AND t2.Location = 'mid'
JOIN Table_Exists t3
ON t1.ID = t3.ID
AND t1.LOCATION = 'top'
AND t3.Location = 'bot';
For more generic solution use PIVOT
:
SELECT
[ID]
,[Top] = [top]
,[Middle] = [mid]
,[Bottom] = [bot]
FROM #Table_Exists t
PIVOT (
MAX(STATUS) FOR LOCATION IN ([top],[mid],[bot])
) AS Piv
Upvotes: 3
Reputation: 66
Use pivot function like this
SELECT
ID,
[top] AS [Top],
[mid] AS Middle,
[bot] AS Bottom
FROM(SELECT
ID,
LOCATION,
STATUS
FROM
Table_Exists) AS SourceTable
PIVOT (AVG(STATUS) FOR LOCATION IN ([top],[mid],[bot])) AS PivotTable
Upvotes: 2