如何在SQL中使用Pivot变量?

时间:2016-08-03 08:29:07

标签: sql sql-server dynamic-sql

我有来自表格Paycode的付费代码和名称 而且我在月交易中有金额。如下:

Paycodes
Code     Name
1        Basic Salary
2        Variable Deduction Amount
3        Fixed/Var Insurance PayCode

MonthlyTransaction
Code     Amount
1        3000
2        10000
1        130000
1        150000
3        120000

我希望它使用pivot

Basic Salary    Variable Deduction Amount  Fixed/Var Insurance PayCode
31000           10000                      120000

我想使用pivot来汇总每个Paycode的金额,我使用了这个: -

DECLARE @data AS NVARCHAR(MAX)
DECLARE @query  AS NVARCHAR(MAX)


--  DECLARE @data TABLE
--(
--   PaycodeName NVARCHAR(max)
--)
--INSERT INTO @data
--        ( PaycodeName )
--select dbo.Paycode.PayCodeName FROM dbo.Paycode 




select @data = Paycode.PayCodeName FROM Paycode


set @query = 'SELECT * FROM (
    SELECT Paycode.Name , MonthlyTransaction.Amount
    From MonthlyTransaction
    LEFT JOIN dbo.Paycode ON Paycode.code = MonthlyTransaction.Paycode
    ) AS s
    PIVOT
    (
        SUM(Amount)
        FOR Paycode.Name IN ('+@data+')
    ) AS pvt '

EXECUTE Sp_executesql @query 

当我打印@data时,它只检索最后一个付费代码! 有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

要获取@data中的所有付费代码

SELECT @data = @data + Paycode.PayCodeName + ', '
FROM Paycode

然后删除最后一个逗号

答案 1 :(得分:0)

这应该可以解决问题

 SELECT 1 Code, 'Basic Salary' Name
 INTO #Paycode
 UNION
 SELECT 2 Code, 'Variable Deduction Amount' Name
 UNION
 SELECT 3 Code, 'Fixed/Var Insurance PayCode' Name

 SELECT 1 Code, 3000 Amount
 INTO #MonthTrans
 UNION
 SELECT 2 Code, 10000 Amount
 UNION
 SELECT 1 Code, 130000 Amount
 UNION
 SELECT 1 Code, 150000 Amount
 UNION
 SELECT 3 Code, 120000 Amount

 DECLARE @data AS NVARCHAR(MAX)

 SELECT @data = ISNULL(@data,'') + '[' +CAST(Code AS varchar) + '], '
 FROM #Paycode

 SELECT @data=SUBSTRING(@data, 0, LEN(@data))


 DECLARE @query  AS NVARCHAR(MAX)

 SELECT @query = 'SELECT * 
 FROM
    #MonthTrans M
 PIVOT ( 
    SUM(Amount) FOR Code IN (' + @data + ')
 ) pvt'


 EXECUTE Sp_executesql @query 


 drop table #paycode
 drop table #MonthTrans

答案 2 :(得分:0)

答案是:

DECLARE @codeNameCol NVARCHAR(max)

SELECT   @codeNameCol= COALESCE(@codeNameCol + ',','') + QUOTENAME(RTRIM(LTRIM(PayCodeName)))
FROM (SELECT DISTINCT PayCodeName FROM Paycode) AS codeNameCol

DECLARE @querys NVARCHAR(max)

Set @querys='
SELECT  *
FROM    ( SELECT    dbo.EmpAssignment.EmployeeId ,
                PayCodeName ,
                Amount
      FROM      dbo.MonthlyTransaction
                LEFT JOIN dbo.Paycode ON Paycode.code = MonthlyTransaction.Paycode
                LEFT JOIN dbo.EmpAssignment ON EmpAssignment.EmpId = MonthlyTransaction.EmpId
                LEFT JOIN dbo.PayrollGroup ON PayrollGroup.PayrollGroup = EmpAssignment.PayrollGroup
    ) DataTable PIVOT
( SUM(Amount) FOR PayCodeName IN ( '+@codeNameCol+' ) ) PivotTable;'

EXEC (@querys)