想要在pivotat列中按LineSubType排序

时间:2016-11-08 16:49:42

标签: sql-server

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(LineSubType) 
                    from TrnsSalaryProcessRegisterDetail 

                    --inner join TrnsSalaryProcessRegister on TrnsSalaryProcessRegisterDetail.SRID=TrnsSalaryProcessRegister.Id
                    --where TrnsSalaryProcessRegisterDetail.LineValue!=null
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
set @query = '
         select a.empid,a.payrollname,a.DepartmentName,s.PeriodName,
            d.*
         from TrnsSalaryProcessRegister s
         inner join mstemployee a on a.id=s.empid
         inner join 
         (
            SELECT SRID,' + @cols + ' 
            from 
            (
                select SRID,LineSubType, LineValue
                from TrnsSalaryProcessRegisterDetail

            ) x
            pivot 
            (
                sum(LineValue)
                for LineSubType in (' + @cols + ')
            ) p 
          ) d
            on s.ID = d.SRID where s.PeriodName=''FY2017-Sep'' and a.payrollname=''EmcoStaff'' order by a.empid asc'
            --print(@query)

            execute(@query);

1 个答案:

答案 0 :(得分:0)

关于这里提供的内容,您看起来想要在连接字段中返回有序的不同列表...只需添加一个组和一个顺序,它应返回LineSubeType的不同值,因此您可能不会更长时间需要明确的条款。

{{1}}