I have a query that returns a single row of data. Let’s say it looks like this (with column headers).
Fruit | Veg | Meats | Nuts |
----------------------------------------
Apple Lettuce Veal Almond
Instead of this, I’d like to return this single row as a two column table, with the column/field name in the leftmost column. Like so:
FieldName | Value |
-----------------------
Fruit Apple
Veg Lettuce
Meats Veal
Nuts Almond
Seems like there should be some non-painful way to make this happen, but if there is I can’t seem to find it. Hit a brick wall. Is this even possible?
Thanks much for any input.
EDIT: The query returns results that aren’t static, so I won’t be able to explicitly define the column headings.
EDIT 2: I’m trying to get some of these suggestions to work, and still can’t get this to function with more than one column. Here’s my code:
SELECT
TOP 10
FieldName,
CAST(FieldValue as varchar(MAX)) As FieldValue
FROM Meter M
UNPIVOT([FieldValue] FOR FieldName IN ([MeterName],[MID])) UP
WHERE ClientNumber = 12300
Every time, I get the error “Msg 8167, Level 16, State 1, Line 4
The type of column “MID” conflicts with the type of other columns specified in the UNPIVOT list.”
I’ve looked this up, and it appears to be an issue related to column types/length, and no matter how I cast the FieldValue, same error. Any thoughts there?
EDIT 3: Resolution to the column conflict…
Casting results from the original table would NOT work, so I had to use a derived table and cast there so that the columns being returned to the PIVOT were all the same data type. Odd, but the only solution I could find that would run.
SELECT
FieldName,
CAST(FieldValue as varchar(MAX)) As FieldValue,
FROM
(
/*
Derived table so that we can control the column
types for everything selected, because PIVOT demands
that every pivoted column be of the same data type and
length.
*/
SELECT
TOP 1
CAST(M.MeterName as varchar(MAX)) As MeterName,
CAST(M.MID as varchar(MAX)) As MID,
CAST(D.DeviceType as varchar(MAX)) As DeviceType
FROM Meter M
INNER JOIN CurrentDevice D ON
D.ClientNumber = M.ClientNumber AND
D.MID = M.MID
WHERE
M.ClientNumber = 12300
) T
UNPIVOT([FieldValue] FOR FieldName IN ([MeterName],[MID],[DeviceType])) UP
For SQL Server 2005+ you can use
UNPIVOT:Here is an SQL Fiddle for you to try.
Updated for new requirement
Ok, so you need dynamic SQL if you don’t know the columns of your table. First, go to this link. Then you can try the follwing: