sql convert single row to key/value columns

大城市里の小女人 提交于 2019-12-04 13:57:50

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/17468196/sql-convert-single-row-to-key-value-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!