将多列放入行中

时间:2014-05-29 23:40:21

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

我做了一些搜索并没有得到一个好的答案。我试图从数据创建一个表,然后在SQL Server中Unpivot它,但无法获得所需的列和行。

IF OBJECT_ID('tempdb..##EXPECT_PERCENTS') IS NOT NULL
   DROP TABLE ##EXPECT_PERCENTS

CREATE TABLE ##EXPECT_PERCENTS (
   PAYOR_ID VARCHAR(40)
   ,TEST_TYPE VARCHAR(40)
   ,[2011-08-31] INT
   ,[2011-09-30] INT
)
GO

INSERT INTO ##EXPECT_PERCENTS VALUES('UHC','UDT','1','2');

select * from ##EXPECT_PERCENTS

SELECT PAYOR_ID, TEST_TYPE, EXPECT
FROM ##EXPECT_PERCENTS
UNPIVOT 
(
  EXPECT FOR EXPECTS IN ([2011-08-31],[2011-09-30])
) AS u

我也试图取消日期,以便有另一个名为“日期”的字段,其中两个日期代表每个数字。第一行应该是:

UHC UDT 1 2011-08-31

1 个答案:

答案 0 :(得分:2)

如果没有unpivot命令,通常可以更轻松地取消对多列的拆分。一种选择是使用CROSS APPLY

select payor_id, test_type, expect, expectdate
from expect_percents
cross apply
(
  select [2011-08-31],'2011-08-31' union all
  select [2011-09-30],'2011-09-30'
) c (expect, expectdate);

另一种选择是使用UNION ALL

select payor_id, test_type, [2011-08-31] expect, '2011-08-31' date
from expect_percents
union all
select payor_id, test_type, [2011-09-30] expect, '2011-09-30' date
from expect_percents;