Problem in dynamic pivoting + sql server 2005

后端 未结 2 1644
孤城傲影
孤城傲影 2021-01-26 03:10

I have a problem. Actually in our application, earlier the customer was allowed to pay 3 installemnt per month but now it can be any number . So I have the earlier query

相关标签:
2条回答
  • 2021-01-26 03:23

    You can build the query dynamically:

    declare @installment_list varchar(max)
    select @installment_list = IsNull(@installment_list,'') + 
        '[' + cast(Installment as varchar(32)) + '],'
    from #tbl
    group by Installment
    
    -- Remove last comma
    set @installment_list = left(@installment_list,len(@installment_list)-1)
    
    declare @dynquery varchar(max)
    set @dynquery = 'select * ' +
        'from #tbl ' +
        'pivot ( ' +
        '   max([Installment]) ' +
        '   for [Installment] ' +
        '   in (' + @installment_list + ') ' +
        ') as pvt'
    
    exec (@dynquery)
    

    Note that table variables are not visible inside the exec(), so I've changed to a temporary variable (#tbl instead of @tbl).

    0 讨论(0)
  • 2021-01-26 03:33

    Row by row, you can't change the number of output columns.

    If I understand correctly, you'll have to build it for the maximum number of columns and give NULL/0 for unused columns.

    Edit: which is what Andomar is doing but he dynamically chooses the maximum number of columns

    0 讨论(0)
提交回复
热议问题