动态旋转+ sql server 2005中的问题

2022-01-22 00:00:00 pivot sql sql-server-2005 tsql sql-server

我有问题.实际上在我们的应用程序中,之前允许客户每月支付 3 次分期付款,但现在可以是任意数字.所以我有更早的查询

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

declare @tbl table([MonthName] varchar(50), [Installment] int)

insert into @tbl select 'Jan',100 union all

select 'Jan',200 union all select 'Jan',300 union all

select 'Feb',100 union all

select 'Feb',200 union all select 'Feb',300



select [MonthName]

        ,[100] as '1st installment'

        ,[200] as '2nd installment'

        ,[300] as '3rd installment'

from

(select [MonthName],[Installment] from @tbl)as x

pivot

(max([Installment]) for [Installment] in

([100],[200],[300]))as pvt

输出是这样的

MonthName   1st installment 2nd installment 3rd installment

Feb             100              200            300

Jan             100              200            300

但正如我所说的,现在分期付款可能会有所不同(比如在 1 个月内可能是 4 个,而在下个月可能是 5 个或 3 个或 6 个),那么在这种情况下如何使动态列旋转?

But as I say that the installments can vary now ( say in 1 month it can be 4 while in next month it can be 5 or 3 or 6), so how can I make a dynamic column pivoting in this case?

提前致谢

推荐答案

您可以动态构建查询:

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)

请注意,表变量在 exec() 中不可见,因此我已更改为临时变量(#tbl 而不是 @tbl).

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

相关文章