我的情况很小..希望你们能帮助我。
我应该查询一个有4列的桌子
AccountNo, ResourceNo, ProductNo, CustomerNo
。
一些帐户没有2个ResourceNo(115和134)
我必须以这样一种方式对其进行查询:我必须为resourceNo
值显示两个动态列,并对accountNo
放置一个“X”,其中包含ResourceNo
' s ..所以AccountNo
没有重复..在这种情况下,透视没有帮助。请仔细研究并帮助我。
答案 0 :(得分:0)
你需要穷人的支点:
例如:
select
AccountNo,
case when sum(case when ResourceNo = 134 then 1 else 0 end) = 0 then '' else 'X' end as Resource_134,
case when sum(case when ResourceNo = 115 then 1 else 0 end) = 0 then '' else 'X' end as Resource_115
from
AccountResource
group by
AccountNo
示例数据:
AccountNo ResourceNo ProductNo CustomerNo
A1 134 P1 C1
A1 134 P2 C1
A1 134 P3 C2
A2 134 P1 C1
A2 115 P1 C4
A2 115 P2 C1
A3 115 P5 C2
示例输出:
AccountNo Resource_134 Resource_115
A1 X
A2 X X
A3 X
对于动态列,您可以执行以下操作:
declare @sql nvarchar(max)
set @sql = ''
select @sql = @sql + ',' + char(13)+char(10)+
'case when sum(case when ResourceNo = ''' + replace(cast(ResourceNo as nvarchar(10)), '''', '''''') + ''' then 1 else 0 end) = 0 then '''' else ''X'' end as "Resource_' + replace(cast(ResourceNo as nvarchar(10)), '"', '""') + '"'
from AccountResource
group by ResourceNo
order by Resourceno
set @sql = 'select AccountNo' + @sql
+ char(13)+char(10)
+ 'From AccountResource '
+ char(13)+char(10)
+ 'group by AccountNo'
+ char(13)+char(10)
+ 'order by AccountNo'
select * from datacheck.dbo.splitmax(@sql, null,null)
exec sp_executesql @sql