I have a SQL query returning 1 row, with multiple column headers:
Col 1 | Col 2 | Col 3
val 1 | Val 2 | Val 3
is there a way to convert this row to 2 columns, i.e. :
Col 1 | Val 1
Col 2 | Val 2
Col 3 | Val 3
this is running on SQLServer 2008 r2
EDIT: Adding a better example
Product_Code | Product_Name | Customer_Name
101 | yummy cake | derps cake shop
is coming from a simple
select p.prod_code, p.prod_name, c.cust_name from product p
inner join customer c on p.id = c.id
type query. What I want to display is:
col heading 1| col heading 2
product_code | 101
Product_Name | yummy cake
customer_name| derps cake shop
Try this
CREATE TABLE #Table1
([Col 1] varchar(5), [Col 2] varchar(5), [Col 3] varchar(5))
;
INSERT INTO #Table1
([Col 1], [Col 2], [Col 3])
VALUES
('val 1', 'Val 2', 'Val 3')
;
SELECT Col,Val FROM
(
SELECT * FROM #Table1
) P
UNPIVOT
(
val FOR Col IN ([Col 1], [Col 2], [Col 3])
) pvt
DROP TABLE #Table1
You can use UNPIVOT in your version of sql server:
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,
Emp3 int, Emp4 int, Emp5 int);
GO
INSERT INTO pvt VALUES (1,4,3,5,4,4);
INSERT INTO pvt VALUES (2,4,1,5,5,5);
INSERT INTO pvt VALUES (3,4,3,5,4,4);
INSERT INTO pvt VALUES (4,4,2,5,5,4);
INSERT INTO pvt VALUES (5,5,1,5,5,5);
GO
SELECT * FROM pvt
--Unpivot the table.
SELECT VendorID, Employee, Orders
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
(Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt;
GO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With