2

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
2

2 Answers 2

3

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';

LiveDemo

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

LiveDemo2

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @lad2025 This was very helpful
If any values for "Status" are 0/null the entire row for that "ID" will be excluded. If Table_Exists is missing data the PIVOT function can be used to return "ID" rows when "Status" is 0/null
2

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

2 Comments

I am getting error message "Error converting data type nvarchar to int." Any thoughts? @Mihai
Is your Status column a nvarchar? If so then CAST(STATUS, int) AS STATUS will let get the average

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.