if object_id('tempdb.dbo.#tb') is not null drop table #tb
create table #tb([Number] int,[StateCode] varchar(10),[Time] datetime)
insert #tb
select 90031,'NewCmd','2010-2-3' union all
select 90031,'ToCustomer','2010-2-4' union all
select 90031,'ToFSC','2010-2-5' union all
select 90032,'NewCmd','2010-2-6' union all
select 90032,'ToCustomer','2010-2-7' union all
select 90032,'ToFSC','2010-2-8' union all
select 90033,'NewCmd','2010-2-9' union all
select 90033,'ToCustomer','2010-2-10' union all
select 90034,'NewCmd','2010-2-11'
declare @sql varchar(8000)
set @sql = 'select Number '
select @sql = @sql + ' , max(case StateCode when ''' + StateCode + ''' then [Time] else null end) [' + StateCode + ']'
from (select distinct StateCode from #tb) as a
set @sql = @sql + ' from #tb group by Number'
exec(@sql)

本文介绍了一种使用T-SQL动态构建复杂查询的方法。通过创建临时表并利用声明变量和字符串拼接技巧,实现了根据不同状态码聚合最大时间的功能。这种方法适用于需要灵活组合查询条件的场景。
2755

被折叠的 条评论
为什么被折叠?



