SQL Returns the following results from table: CowTracking
ID cow_id barn_id
-- ------ -------
19 5 3
20 5 2
21 5 9
22 5 1
I am trying to get the following results with a PIVOT in SQL
cow_id barn1 barn2 barn3 barn4
------ ----- ----- ----- -----
5 3 2 9 1
This is the code I have so far.
SELECT *
FROM
(
SELECT TOP 4 *
FROM CowTracking
WHERE cow_id = 5
) AS DataTable
PIVOT
(
MIN(barn_id) **IDK what function to use and which column to use it on**
FOR ID ??<---**NOT SURE**
IN
(
[barn1], [barn2], [barn3], [barn4]
)
) AS PivotTable
ERRORS: Error converting data type nvarchar to int
The incorrect value "barn1" is supplied in the PIVOT operator
NOTE: The barn_id is a varchar. It will not be possible to change the datatype.
I am not trying to add/multiply/aggregate or whatever. I am simply trying to move the row to a column
How would I go about doing this? Is this the correct thought process?
Do I even need to use PIVOT?
As there is no
barn1..4
in your tables, you somehow have to replace theID
's with their correspondingbarn
s.One solution using
PIVOT
might be like thisanother solution using
CASE
andGROUP BY
could bebut in essence, this all boils down to hardcoding an
ID
to abarn
.Edit
If you always return a fixed number of records, and using SQL Server you might make this a bit more robust by
ROW_NUMBER
to each resultSQL Statement
Test script