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

Problem in dynamic pivoting + sql server 2005(动态旋转+ sql server 2005中的问题)
本文介绍了动态旋转+ sql server 2005中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题.实际上在我们的应用程序中,之前允许客户每月支付 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).

这篇关于动态旋转+ sql server 2005中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)