在数据透视表上将十进制转换为字符串

时间:2016-10-11 03:43:04

标签: sql sql-server tsql

示例代码

Declare
    @table1  VARCHAR(MAX)

Set @table1 = 'Select * from @tempTbl'


Declare
    @List   VARCHAR(MAX),
    @Pivot  VARCHAR(MAX)

Select @List = ISNULL(@List + ',', '') + TrxCd From TransacMaster Where Module = 'CB' 

Set @Pivot = '
SELECT ROW_NUMBER() OVER (ORDER BY DebtorCd ASC) As RowIndex, *
FROM (
    Select Distinct
        c.UserId, 
        d.Name, 
        b.TrxCd 
        SUM(b.Amount) As Amount
    From tbl_InvH a
    Inner Join tbl_InvD b on a.subCd = b.subCd and a.InvNo = b.InvNo 
    Left Join tbl_User c On a.UserId = c.UserId
    Left Join tbl_Personnel d on c.PersonnelId = d.PersonnelId
    Group By c.UserId, d.Name, b.TrxCd
) as s
PIVOT
(
    SUM(Amount)
    FOR TrxCd IN (' + @List + ')
)AS pvt'


Declare @Result nVarchar(MAX)

Set @Result = @table1 + ' 
Union All 
' + @Pivot

Exec sp_executesql @Result 

我想将字段数量从十进制转换为字符串,因为在此之后我想要UNION与另一个表,但字段数量和来自另一个表的字段是不同的类型。

我尝试过CAST(SUM(Amount)为Varchar)但错误:

' CAST'不是公认的聚合函数。

我无法在主选择上转换,因为TrxCd的字段是动态的

Pivot的结果

RowIndex  |  UserId   |   Name        |   IT01   |   IT02   |   IT03   |  IT04
--------------------------------------------------------------------------------
1         |   John    |   John Ivy    |   2,000  |   2,000  |   1,000  |  5,000
2         |   Merry   |   Merry Ish   |   1,000  |   1,000  |   1,000  |  6,000

其他表

RowIndex  |  UserId   |   Name        |   Transac1   |   Transac2   |   Transac3   |  Transac4
-------------------------------------------------------------------------------------------------
1         |   John    |   John Ivy    |   Trx Bank A |   Trx Bank B |   Trx Bank C |  Trx Bank D

如何从数据透视转换字段金额。

1 个答案:

答案 0 :(得分:0)

由于动态特性,您可以使用相同的@List表达式Select @List = ISNULL(@List + ',', '') + TrxCd From TransacMaster Where Module = 'CB'并为主要选择中的动态投射创建第二个;

Select @List2 = ISNULL(@List2 + ',', '') + 'cast(' + TrxCd + 'as varchar)' From TransacMaster Where Module = 'CB'

然后使用此列和其他列来替换主选择中的星号;

'SELECT ROW_NUMBER() OVER (ORDER BY DebtorCd ASC) As RowIndex, UserId, Name,' + @List2 +'....'