TABLE1:(ID为索引)
ID Type
========
1 A
2 C
3 A
4 BTABLE2:
ID Name
========
1 张三
1 王五
2 张三
2 李四
3 李四
3 张三
3 王五
4 王五
4 李四说明:TABLE1中的ID是顺序增加的,TYPE值为A、B、C之一,TABLE1中的ID与TABLE2中的ID是一对多的关系,我想得出每个人ABC类型出现的次数,如下:
Name A B C
=================
张三 2 0 1
李四 1 1 1
王五 2 1 0
ID Type
========
1 A
2 C
3 A
4 BTABLE2:
ID Name
========
1 张三
1 王五
2 张三
2 李四
3 李四
3 张三
3 王五
4 王五
4 李四说明:TABLE1中的ID是顺序增加的,TYPE值为A、B、C之一,TABLE1中的ID与TABLE2中的ID是一对多的关系,我想得出每个人ABC类型出现的次数,如下:
Name A B C
=================
张三 2 0 1
李四 1 1 1
王五 2 1 0
解决方案 »
- 基于PLC的四级传送带控制系统设计
- oracle存储过程求教 如何将一个表的数据插入到另外一张表
- 求一条sql语句 (sql server 2000)
- 为什么不是死锁而是阻塞?
- 关于sqlserver的job内容
- 急!!在线等!高分求助各位sql精英,一条SQL汇总语句,功力好的请进!
- 数据库性能突然变慢,怎么办?
- 本地数据库请问如何通过代理服务器(socket端口 1080,http:8080) 连接到远程的数据库上?
- 请问各位做过图书馆管理系统的高手们
- SQL Server,有一表的字段是自动增长标志位(Id),如何在插入一新纪录时同时获得Id值,大家提提可行方案吧
- adoconnect控件连接出现的问题
- 如何得到库存数量
b.Name,
A=sum(case Type when 'A' then 1 else 0 end),
B=sum(case Type when 'B' then 1 else 0 end),
C=sum(case Type when 'C' then 1 else 0 end)
from
Table1 a,Table2 b
where
a.ID=b.ID
group by
b.Name
insert into @t1 select 1,'A'
insert into @t1 select 2,'C'
insert into @t1 select 3,'A'
insert into @t1 select 4,'B'declare @t2 table(ID int,name varchar(10))
insert into @t2 select 1,'张三'
insert into @t2 select 1,'王五'
insert into @t2 select 2,'张三'
insert into @t2 select 2,'李四'
insert into @t2 select 3,'李四'
insert into @t2 select 3,'张三'
insert into @t2 select 3,'王五'
insert into @t2 select 4,'王五'
insert into @t2 select 4,'李四'
select
b.Name,
A=sum(case Type when 'A' then 1 else 0 end),
B=sum(case Type when 'B' then 1 else 0 end),
C=sum(case Type when 'C' then 1 else 0 end)
from
@T1 a,@T2 b
where
a.ID=b.ID
group by
b.Name
/*Name A B C
---------- ----------- ----------- -----------
李四 1 1 1
王五 2 1 0
张三 2 0 1
*/
insert into #t1 select 1,'A'
insert into #t1 select 2,'C'
insert into #t1 select 3,'A'
insert into #t1 select 4,'B'
create table #t2(ID int,name varchar(10))
insert into #t2 select 1,'张三'
insert into #t2 select 1,'王五'
insert into #t2 select 2,'张三'
insert into #t2 select 2,'李四'
insert into #t2 select 3,'李四'
insert into #t2 select 3,'张三'
insert into #t2 select 3,'王五'
insert into #t2 select 4,'王五'
insert into #t2 select 4,'李四'declare @sql varchar(256)
select @sql = ''
select @sql = @sql + ',[' + type + '] = sum(case type when ''' + type + ''' then 1 else 0 end)' from #t1 group by typeselect @sql
exec ('select b.name ' + @sql + ' FROM #t1 a,#t2 b where a.ID=b.ID group by b.Name')