将多列合并为单个列和逗号

时间:2015-12-04 16:09:48

标签: sql-server

我需要帮助。如果列名是数字,我想将数据库的输出合并为单个列。

输出内容应如下所示:

Employeeno命名其他decing xxxxxxxxx james 249-14000,250-21000,133-45000

其中“249”,“250”,“133”是从数据透视查询派生的列名。请参阅下面的代码:

DECLARE @cols nvarchar(MAX)
SELECT @cols = stuff((
           SELECT ',' + quotename(COSTITEM_DED_CODE) FROM temp
           GROUP BY COSTITEM_DED_CODE ORDER BY COSTITEM_DED_CODE FOR xml path(''), TYPE
          ).value('.', 'nvarchar(max)')
          ,1,1,'')
/*****Create a new row at the bottom as a vertical total*******/
DECLARE @vert_total nvarchar(MAX)
SELECT @vert_total = stuff((
           SELECT ',sum(' + quotename(COSTITEM_DED_CODE) + ')' 
           FROM temp
           GROUP BY COSTITEM_DED_CODE 
           ORDER BY COSTITEM_DED_CODE 
           FOR xml path(''), TYPE
          ).value('.', 'nvarchar(max)')
          ,1,1,'')
/***** Create a new column at the end as a horizontal total. ******/
DECLARE @horiz_total nvarchar(MAX)
SELECT @horiz_total = stuff((
           SELECT '+isnull(' + quotename(COSTITEM_DED_CODE) + ',0)' 
           FROM temp
           GROUP BY COSTITEM_DED_CODE 
           ORDER BY COSTITEM_DED_CODE
           FOR xml path(''), TYPE
          ).value('.', 'nvarchar(max)')
          ,1,1,'')
/***** Avoid NULL in the output by converting all NULLs to 0.*****/ 
DECLARE @isnulls nvarchar(MAX)
SELECT @isnulls = stuff((
           SELECT ',isnull(' + quotename(COSTITEM_DED_CODE) + ',0) as '+quotename(COSTITEM_DED_CODE) 
           FROM temp 
           GROUP BY COSTITEM_DED_CODE
           ORDER BY COSTITEM_DED_CODE
           FOR xml path(''), TYPE
          ).value('.', 'nvarchar(max)')
          ,1,1,'')
/***** Generate the pivot, saving the result to a new temporary table*******/
DECLARE @query nvarchar(MAX)
SET @query = 'select SNO,EMPLOYEENO,AFFORDABLE,NAMES,DOB,ACNTNO,AGE,MAXLOANTERM,MAXLOANTERM2,OTHERDEDUCT,' + @cols + ',' + @horiz_total + ' as TOTAL 
              into temp2
              from (select SNO, EMPLOYEENO, AFFORDABLE, NAMES, DOB, ACNTNO, AGE, MAXLOANTERM, MAXLOANTERM2, OTHERDEDUCT, COSTITEM_DED_CODE, INCOMEAMOUNT from temp) x
              pivot (sum(incomeamount) for COSTITEM_DED_CODE in (' + @cols + ')) p
              select EMPLOYEENO as EMPLOYEENO, '+@isnulls+', isnull(Total,0) as Total 
              from temp2 
              union all
              select ''TOTAL'', '+@vert_total+',sum(Total) 
              from temp2'
EXECUTE(@query)

0 个答案:

没有答案