我有下表需要转换为数据透视表,两个字段都包含相同的条目,并且需要在数据透视表中表示条目的计数。条目的计数必须按条目类型(如A或B)进行分组。
表
X Y
-----------
A B
A C
D B
B C
C C
D E
D B
F C
枢轴
A Or B C Or D E Or F
A Or B 1 2 0
C Or D 2 1 1
E Or F 0 1 0
答案 0 :(得分:0)
如果您的群组是动态的,则必须构建动态查询。
declare @t table(X char(1), Y char(1))
insert into @t values
('A', 'B')
, ('A', 'C')
, ('D', 'B')
, ('B', 'C')
, ('C', 'C')
, ('D', 'E')
, ('D', 'B')
, ('F', 'C')
Select [\] = G2, isnull([A Or B], 0), isnull([C Or D], 0), isnull([E Or F], 0)
From (
Select G1 = g1.name, G2 = g2.name, total = count(*) From @t t
Inner Join (values('A Or B', 'A', 'B'), ('C Or D', 'C', 'D'), ('E Or F', 'E', 'F')) g1(name, X, Y) on t.X = g1.X or t.X = g1.Y
Inner Join (values('A Or B', 'A', 'B'), ('C Or D', 'C', 'D'), ('E Or F', 'E', 'F')) g2(name, X, Y) on t.Y = g2.X or t.Y = g2.Y
Group By g1.name, g2.name
) as d
Pivot (
max(total)
For G1 In ([A Or B], [C Or D], [E Or F])
) as piv