实际表中的数据表示两个类别之间的交集(例如a和b是类别)。我拥有的数据有多个类别。在输出表中,我需要显示这些类别之间的交集。
这是实际的表数据。样本数据
col1 Category IntersectedCategory Count
----------------------------------------------
1 a g 12
2 b f 12
3 a a 260
4 c I 38
5 d h 39
6 b g 12
7 b h 27
8 c c 114
9 a h 60
10 a d 57
11 e e 137
12 f h 15
13 g I 12
14 d g 12
15 e f 34
16 c b 15
17 h h 190
18 f f 96
19 c d 14
20 e d 46
21 g f 12
22 e g 12
23 c f 12
24 g g 97
25 d I 72
26 b b 116
27 c h 32
28 b I 45
29 e h 15
30 c g 6
31 a b 16
32 I I 361
33 I f 55
34 a e 38
35 e I 68
36 d d 142
37 g h 6
38 a f 33
39 e b 21
40 b d 21
41 a c 29
42 a I 114
43 I h 81
44 e c 6
45 d f 29
预期输出:
list a b
----------------
a 20 5
b 5 25
答案 0 :(得分:2)
您可以为此使用动态SQL。
用列名构建一个变量,然后在其上使用PIVOT。
示例代码段:
-- using a temporary table for demonstration purposes.
IF OBJECT_ID('tempdb..#TestTable') IS NOT NULL DROP TABLE #TestTable;
CREATE TABLE #TestTable (col1 int identity(1,1) primary key, Category varchar(8), IntersectedCategory varchar(8), [Count] int);
-- Small set of sample data
insert into #TestTable (Category, IntersectedCategory, [Count]) values
('a','a',20)
,('a','b',5)
,('b','a',5)
,('b','b',25)
;
-- Generating the column names
declare @cols varchar(max);
select @cols = concat(@cols+', ', quotename(IntersectedCategory))
from #TestTable
group by IntersectedCategory
order by IntersectedCategory;
-- constructing the sql statement that uses a PIVOT
declare @DynSql varchar(max);
set @DynSql = 'select *
from (select Category as list, IntersectedCategory as col, [Count] as total from #TestTable) as src
pivot (SUM(total) for col in ('+ @cols +')) as pvt
order by list';
-- select @DynSql as DynSql; -- Just to check how the sql looks like
-- running the generated SQL statement
exec(@DynSql);
结果:
list a b
---- -- --
a 20 5
b 5 25