SQL Server - 整合数据

时间:2016-10-20 16:22:44

标签: sql-server

以下是查询和结果

查询

SELECT Job#, Doc#, Value, Description FROM Table

结果

Job#    Doc#,    Value,     Description
1000     1         100       paint house
1000     2           0       clean floors
1001     1          90       install roof
1001     2           0       install boiler
1001     3           0       install elevator

我想通过Job#创建单行,其中Doc#= 1,但是将Doc添加到Doc#> 1作为新字段的单行,即如果有15个文档Doc#(1-15)那么该行应该有14个新字段,看起来像这样:

期望的结果

Job#    Doc#,  Value,  Description,  Desc2,          Desc3,           ... Desc14
1000     1       100   paint house   clean floors
1001     1        90   install roof  install boiler  install elevator

如何编写查询以达到预期效果?

1 个答案:

答案 0 :(得分:2)

考虑到您已经拥有Doc#

,您可以使用动态条件聚合
slice1 = 4dmatrix(:,:,1,1)
slice2 = 4dmatrix(:,:,1,2)

返回

Declare @SQL varchar(max) = ''
Select @SQL = @SQL+',Desc'+cast([Doc#] as varchar(25))+'=max(case when [Doc#]='+cast([Doc#] as varchar(25))+' then Description else '''' end)'
 From (Select Distinct [Doc#] From YourTable where [Doc#]>1) A 
 Order by [Doc#]

Set @SQL ='
Select [Job#]
      ,[Doc#] = min([Doc#])
      ,Value  = max(Value)
      ,Description = max(case when [Doc#]=1 then Description else '''' end)'+@SQL+'
From YourTable
Group By [Job#]
'
Exec(@SQL)