Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql convert single row to key/value columns

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
like image 334
Jay Avatar asked Oct 12 '25 19:10

Jay


2 Answers

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
like image 64
bvr Avatar answered Oct 14 '25 17:10

bvr


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
like image 31
Danila Polevshchikov Avatar answered Oct 14 '25 17:10

Danila Polevshchikov