小编典典

动态数据透视+ SQL Server 2005中的问题

sql

我有个问题。实际上,在我们的应用程序中,较早的客户被允许每月支付3安装费,但现在可以为任意数量。所以我有较早的查询

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),那么在这种情况下如何进行动态列透视?

提前致谢


阅读 142

收藏
2021-04-15

共1个答案

小编典典

您可以动态构建查询:

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)。

2021-04-15