3

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

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
4

2 回答 2

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
于 2013-07-04T10:52:02.843 回答
3

您可以在您的 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
于 2013-07-04T10:45:04.133 回答