我有两张桌子
Index | Name | GroupIndex \\table1
1 | A | 1
2 | A | 1
3 | A | 2
Index | GroupName \\table2
1 | G1
2 | G2
我希望我的结果是
Index | Name | G1 | G2
1 | A | 2 | 1
我需要显示按Name
分组的GroupIndex
的条目数,但是采用列格式。
我无法从另一个表中找到一种动态添加列的方法。你能救我一下吗?
答案 0 :(得分:1)
create table #table1 ([Index] int,Name char(1), GroupIndex int)
create table #table2 ([Index] int,GroupName char(2))
insert into #table1 values
(1,'A',1),
(2,'A',1),
(3,'A',2)
insert into #table2 values
(1,'G1'),
(2,'G2')
--select * from #table1
--select * from #table2
select * from
(select t1.[GroupIndex] as [Index], t1.Name, t2.[Index] as gi, t2.GroupName
from #table1 t1
inner join #table2 t2 on t2.[Index] = t1.[Index]) as s
PIVOT
(max(gi) FOR GroupName in (G1,G2)) as pvt
--RESULTS--
Index Name G1 G2
1 A 1 2
答案 1 :(得分:1)