需要转动或交叉表格,但不能以传统方式。请

时间:2012-01-05 22:32:40

标签: tsql pivot crosstab

我的情况很小..希望你们能帮助我。

我应该查询一个有4列的桌子   AccountNo, ResourceNo, ProductNo, CustomerNo
一些帐户没有2个ResourceNo(115和134)

我必须以这样一种方式对其进行查询:我必须为resourceNo值显示两个动态列,并对accountNo放置一个“X”,其中包含ResourceNo' s ..所以AccountNo没有重复..在这种情况下,透视没有帮助。请仔细研究并帮助我。

另见

  

Poor Man's SQL Pivot.

另见

  

Sql Pivot Query with Dynamic Columns

1 个答案:

答案 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