使用动态行/ Nvarchars将行转换为列

时间:2017-11-22 06:02:22

标签: sql sql-server database pivot

我有点卡住了,我希望有人能指出我正确的方向。我试图将表格从x行压平成多列。这只是一个示例,真实版本包含可能随时更改的更多行。

/*
HELLO  |  WORLD   |  FOO   |  BAR
 0          0         0        0
*/

CREATE TABLE #HI
(
ID INT IDENTITY(1,1),
COLNAME NVARCHAR(255) DEFAULT('MISSING'),
VAL INT DEFAULT(0)
);

INSERT INTO #HI(COLNAME)VALUES (N'HELLO'),(N'WORLD'),(N'FOO'),(N'BAR') - 这可能会在一天内发生变化,因此硬编码不一定是动态名称。

SELECT  *
FROM 
(
SELECT val, COLNAME
FROM #HI) sourcetbl
PIVOT (MAX(COLNAME) FOR COLNAME IN (
[a]
)) AS pvt
--i think i could use dynamic sql .. haven't looked into this option much yet.  I'm hoping pivot will work
SELECT DISTINCT  COLNAME   FROM 
  #HI A 
  CROSS APPLY 
  ( SELECT COLNAME + ',' FROM #HI B 
  WHERE A.id = B.id ORDER By COLNAME FOR XML PATH('') ) AS C (DerivedColumn)

DROP TABLE #HI;

0 个答案:

没有答案