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?