如何将记录汇总到SQL Server中的多个列

时间:2016-08-19 15:48:46

标签: sql sql-server

很抱歉,如果标题没有意义,但我似乎无法找到我正在尝试做什么的话

我知道如何使用group by function和SQL服务器中的sum,max值创建枢轴。但是,我的问题是这个

我有这样的数据:

Filename     Branch   Name         
1              1      Joe Test     
2              2      Joseph Test  
3              3      Smith Test

每个文件名都有多个借用者关联,当我这样做时,我需要将borrowerid加入到文件名表中:

Filename     Branch     Name        Borrowerid
1              1         Joe Test    123
1              1         Joe Test    345
1              1         Joe Test    678
2              2         Joseph Test 412
2              2         Joseph Test 214
3              3         Smith Test  333

如何将每个借款人放在自己的专栏中,如借款人1,借款人2,借款人?

例如

Filename    Branch     Name      BorrowerId   BorrowerId2   BorrowerId3 
1            1        Joe Test     123          345            678
2            2        Joseph Test  412          214
3            3        Smith Test   333      

请协助帮助解决此问题

谢谢

1 个答案:

答案 0 :(得分:1)

PIVOT和/或DYNAMIC PIVOT是您正在寻找的,但是,我使用存储过程来处理我的大量动态枢轴

Exec [prc-Pivot] 'Select *,NewCol=concat(''Borrowerid'',Row_Number() over (Partition By FileName,Branch,Name Order By Borrowerid)) from YourTable','NewCol','max(Borrowerid)[]','FileName,Branch,Name','count(*)[Records]'

返回

FileName    Branch  Name         Records    Borrowerid1 Borrowerid2   Borrowerid3
1           1       Joe Test      3         123         345           678
2           2       Joseph Test   2         214         412           NULL
3           3       Smith Test    1         333         NULL          NULL

存储过程

CREATE PROCEDURE [dbo].[prc-Pivot] (
    @Source varchar(1000),          -- Any Table or Select Statement
    @PvotCol varchar(250),          -- Field name or expression ie. Month(Date)
    @Summaries varchar(250),        -- aggfunction(aggValue)[optionalTitle]
    @GroupBy varchar(250),          -- Optional additional Group By 
    @OtherCols varchar(500) )       -- Optional Group By or aggregates
AS

--Exec [prc-Pivot] 'Select Year=Year(TR_Date),* From [Chinrus-Series].[dbo].[DS_Treasury_Rates]','''Q''+DateName(QQ,TR_Date)','avg(TR_Y10)[-Avg]','Year','count(*)[Records],min(TR_Y10)[Min],max(TR_Y10)[Max],Avg(TR_Y10)[Avg]'
--Exec [prc-Pivot] '#Temp','Attribute','max(Description)[]','ID','count(*)[Records]'

Set NoCount On

Declare @Vals varchar(max),@SQL varchar(max);
Set @Vals = ''
Set @OtherCols= IsNull(', ' + @OtherCols,'')
Set @Source = case when @Source Like 'Select%' then @Source else 'Select * From '+@Source end
Create Table #TempPvot  (Pvot varchar(100))
Insert Into #TempPvot
Exec ('Select Distinct Convert(varchar(100),' + @PvotCol + ') as Pvot FROM (' + @Source + ') A')
Select @Vals = @Vals + ', isnull(' + Replace(Replace(@Summaries,'(','(CASE WHEN ' + @PvotCol + '=''' + Pvot +  ''' THEN '),')[', ' END),NULL) As [' + Pvot ) From #TempPvot Order by Pvot
Drop Table #TempPvot
Set @SQL = Replace('Select ' + Isnull(@GroupBy,'') + @OtherCols + @Vals + ' From (' + @Source + ') PvtFinal ' + case when Isnull(@GroupBy,'')<>'' then 'Group By ' + @GroupBy + ' Order by ' + @GroupBy else '' end,'Select , ','Select ')
--Print @SQL
Exec (@SQL)