另一个表

时间:2016-10-03 16:03:12

标签: sql sqlite

我有两张桌子

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的条目数,但是采用列格式。

我无法从另一个表中找到一种动态添加列的方法。你能救我一下吗?

2 个答案:

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

创建一个按名称对用户进行分组的数据透视表,然后使用每个组的和函数计算其组。

SELECT
    Sum(case when tbl2.[index]=1 THEN 1 ELSE 0 end ) AS G1,
    SUM(case when tbl2.[index]=2 THEN 1 ELSE 0  end ) AS G2
 FROM tbl1
join tbl2 on tbl2.[index] = tbl1.GroupIndex group by tbl1.Name

enter image description here

相关问题