将动态文本数据行转换为多个列

时间:2016-03-11 03:56:40

标签: sql sql-server tsql pivot

我试图将包含多行的结果表转换为多列。以下是我之前和之后的样本结果:

之前:

enter image description here

后:

enter image description here

here得到一些想法,但仍然没有运气。

更新1:

select @cols = STUFF((select ',' + QUOTENAME(institution) + ',' +        QUOTENAME(intstatus)
                From @temp
                group by refno,frmstatus
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')

我不知道如何将每列插入数据透视查询

set @query = 'select refno, frmstatus,' + @cols + '
from (
     select refno, frmstatus, institution, intstatus from #temp
) x
pivot
(
???????
)

2 个答案:

答案 0 :(得分:1)

请尝试以下查询:

CREATE TABLE #temp(refno nvarchar(20), firmstatus nvarchar(20), institution nvarchar(20), intstatus nvarchar(20), ranking int)
DECLARE @qu NVARCHAR(MAX), @pcol NVARCHAR(MAX)


INSERT INTO #temp
SELECT  
    *,
    ROW_NUMBER() OVER (PARTITION BY refno ORDER BY institution ASC) AS ranking
FROM temp

SELECT @pcol=  
 STUFF(( 
  SELECT 
        DISTINCT N', Institution'+ CAST (ranking AS NVARCHAR(25)) +', '+  N'Intstatus'+ CAST (ranking AS NVARCHAR(25))
  FROM #temp
  FOR XML PATH('')),1,1,'')

SET @qu=N'SELECT refno, firmstatus,'+ @pcol +  
N' FROM 
    (
    select refno,firmstatus,ColData,colheader+ CAST(ranking as varchar) as colnames from 
    (select * from #temp)s
    UNPIVOT
    (ColData for colheader in ([institution], [intstatus])) up

    )S
  PIVOT
  (MAX(ColData) FOR colnames IN ('+@pcol +N')) AS piv'

EXEC sp_executesql @qu -- execute the dynamic sql
DROP TABLE #temp -- remove the temp table

上面脚本中的临时表创建如下

--create table temp( refno nvarchar(20), firmstatus nvarchar(20), institution nvarchar(20), intstatus nvarchar(20))
--insert into temp  values 
--('AAA/1','Active','InstA','Ongoing'),
--('AAA/1','Active','InstB','Ongoing'),
--('AAA/1','Active','InstC','Ongoing'),
--('AAA/2','Active','InstA','Ongoing'),
--('AAA/2','Active','InstB','Ongoing')

收到的结果:

enter image description here

答案 1 :(得分:0)

如果重复的列数很小且受限制,您可以使用简单的解决方案:

WITH A AS (
SELECT *, 
ROW_NUMBER() OVER(PARTITION BY refno, fmstatus ORDER BY institution) n
FROM myTable
),

B AS (
SELECT refno, fmstatus,
CASE WHEN n=1 THEN institution END institution,
CASE WHEN n=1 THEN intstatus END intstatus,
CASE WHEN n=2 THEN institution END institution1,
CASE WHEN n=2 THEN intstatus END intstatus1,
CASE WHEN n=3 THEN institution END institution2,
CASE WHEN n=3 THEN intstatus END intstatus2
FROM A
)

SELECT refno, fmstatus,
MAX(institution) institution,
MAX(intstatus) intstatus,
MAX(institution1) institution1,
MAX(intstatus1) intstatus1,
MAX(institution2) institution2,
MAX(intstatus2) intstatus2
FROM B
GROUP BY refno, fmstatus

否则使用PIVOT