sql将单行转换为键/值列

时间:2013-07-04 10:40:52

标签: sql sql-server sql-server-2008-r2

我有一个SQL查询返回1行,有多个列标题:

Col 1 | Col 2 | Col 3
val 1 | Val 2 | Val 3

有没有办法将此行转换为2列,即:

Col 1 | Val 1
Col 2 | Val 2
Col 3 | Val 3

这是在SQLServer 2008 r2上运行

编辑:添加更好的例子

   Product_Code | Product_Name | Customer_Name
   101          | yummy cake   | derps cake shop

来自一个简单的

select p.prod_code, p.prod_name, c.cust_name from product p 
inner join customer c on     p.id = c.id

类型查询。我想要展示的是:

   col heading 1| col heading 2
   product_code | 101
   Product_Name | yummy cake
   customer_name| derps cake shop

2 个答案:

答案 0 :(得分:4)

试试这个

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

答案 1 :(得分:2)

您可以在您的sql server版本中使用UNPIVOT:

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