求一句有点难度的SQL语句,各位高手进来帮帮我!!

java1987 2005-12-14 04:55:16
name(名称) (jb)级别

A 1
A 2 ---表AB1
A 3
B 1

算出每个名称 级别个数
结果:

name a1 a2 a3

A 1 1 1 --表AB2
B 1 0 0

我想把表A数据查出来 以上面结果的形式添进表A2请各位帮忙了!
--测试环境!!!!
create table ab1
(name char,
jb int)
go
insert a1
select 'A',1 UNION ALL
select 'A',2 UNION ALL
select 'A',3 UNION ALL
select 'B',1
go
create table ab2
(name char,a1 int default 0 ,a2 int default 0 ,a3 int default 0)
go
...全文
179 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
liuxue88 2005-12-15
  • 打赏
  • 举报
回复
declare @AB1_name varchar(20),@AB1_jb varchar(20)
declare acursor cursor for select * from AB1
open acursor
fetch next from acursor into @AB1_name,@AB1_jb
while @@FETCH_STATUS = 0
begin
if not exists (select * from AB2 where name=@AB1_name )
begin
insert AB2 (name) values (@AB1_name)
end
if @AB1_jb = 1
update AB2 set a1=1
if @AB1_jb = 2
update AB2 set a2=1
if @AB1_jb = 3
update AB2 set a3=1
fetch next from acursor into @AB1_name,@AB1_jb
end
close acursor
deallocate acursor
---------------------------------
应该不是最好的方法,不过可以得到你要的结果。我是SQL新手,只会这样的笨法了:-)
lxw99 2005-12-15
  • 打赏
  • 举报
回复
我觉得以上都不是完全之法a在有个4,5,6

SQL Server 啊 努力 奋斗-----------------------------------------------------

lxw99 2005-12-15
  • 打赏
  • 举报
回复
我觉得以上都不是完全之法

SQL Server 啊 努力 奋斗-----------------------------------------------------

lsqkeke 2005-12-15
  • 打赏
  • 举报
回复
写错个字段: 改下
insert into ab2
select name,a1=sum(case jb when 1 then 1 else 0 end),a2=sum(case jb when 2 then 1 else 0 end),
a3=sum(case jb when 3 then 1 else 0 end)
from ab1 group by name
lsqkeke 2005-12-15
  • 打赏
  • 举报
回复
insert into ab2
select name,a1=sum(case jb when 1 then 1 else 0 end),a2=sum(case jb when 2 then 1 else 0 end),
a3=sum(case ib when 3 then 1 else 0 end)
from ab1 group by name
lxzm1001 2005-12-15
  • 打赏
  • 举报
回复
select * from ab1
select name,a1=sum(case when jb=1 then 1 else '' end),a2=sum(case when name='a' and jb=2 then 1 else '' end),
a3=sum(case when name='a' and jb=3 then 1 else '' end)
from ab1 group by name
hpym365 2005-12-15
  • 打赏
  • 举报
回复
insert into ab2
select name,a1=sum(case when jb=1 then 1 else '' end),a2=sum(case when name=aa.name and jb=2 then 1 else '' end),
a3=sum(case when name=aa.name and jb=3 then 1 else '' end)
from a1 aa group by name
这个一定对 看看吧
java1987 2005-12-14
  • 打赏
  • 举报
回复
请各位高手帮帮忙啊 小弟急 在线等啊!

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧