问一个SQL语句,实现数据合并的问题

azurebz 2006-08-15 05:32:32
问一个SQL语句,实现查下面的表后(假设为A表):
A B
1 a
1 b
1 c
2 e
3 f
出来的结果是:
A B
1 a b c
2 e
3 f

还有推荐大家进我的群:20951774
...全文
203 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
chjpeng 2006-08-15
  • 打赏
  • 举报
回复
可以参考邹建的一个回复:



zjcxc(邹建) 于 2005-6-6 15:12:10

--如果楼主的目的是为了按列1,列2合并列3,则使用函数

--示例

--测试数据
create table 表(列1 varchar(10),列2 varchar(10),列3 varchar(10))
insert 表 select 'majun','马俊','建银物业'
union all select 'majun','马俊','综合部'
union all select 'majun','马俊','工程部'
union all select 'majun','马马','综合部'
union all select 'majun','马马','工程部'
go

--处理函数
create function f_str(@列1 varchar(10),@列2 varchar(10))
returns varchar(8000)
as
begin
declare @s varchar(8000)
set @s=''
select @s=@s+','+列3 from 表
where 列1=@列1 and 列2=@列2
return(stuff(@s,1,1,''))
end
go

--调用函数实现查询
select 列1,列2,列3=dbo.f_str(列1,列2) from 表
group by 列1,列2
go

--删除测试
drop table 表
drop function f_str

/*--结果

列1 列2 列3
---------- ---------- ---------------------------
majun 马俊 建银物业,综合部,工程部
majun 马马 综合部,工程部

(所影响的行数为 2 行)

--*/
landy_shasha 2006-08-15
  • 打赏
  • 举报
回复
mark
QuinsonYue 2006-08-15
  • 打赏
  • 举报
回复
deadshot123的例子真是妙 哈哈
artak 2006-08-15
  • 打赏
  • 举报
回复
mark
deadshot123 2006-08-15
  • 打赏
  • 举报
回复
1,将某一行转为列,作用:

如果我们在输入成绩时,一般要按学号,学期,课程号,成绩来输入,但是,我们要打印全班的成绩里就是要把课号改为列了,就如果上面的,那样该怎么做呀 ?

比如:
个人成绩表:
学号  课号   成绩
01   01    80
01   02    79
01   03    88
02   01    87
02   02    77
02   03    68

用SQL把上表转换为:
学号  课号01  课号02  课号03
01   80     79    88
02   87     77    68

---------建表----------
create table tab_score
(
bid int identity(0,1) primary key ,--流水号
sid varchar(20) not null,--学生号
cid varchar(20) not null,--课程号
score int--成绩
)
insert into tab_score select's01','c01','90' union all select 's01','c02','92' union all select 's01','c03','93'
union all select 's02','c01','81' union all select 's02','c02','82'

/*---固定列的写法,后面的写法将是根据有几个课程id来动态组装中间的sum语句,然后加上头尾就成了,
理解了这种'静态'写法,剩下的只是'动态'组装中间sum语句的工作----*/
select * from tab_score
select sid,sum(case cid when 'c01' then score else '0' end) as 'c01',
sum(case cid when 'c02' then score else '0' end) as 'c02',
sum(case cid when 'c03' then score else '0' end) as 'c03'
from tab_score group by sid
-----'动态'列的写法,定义一个变量来组装中间的sum语句,其中用到子查询表(原来不用这方法一直会出现重复列)-------
declare @s varchar(1000)
set @s=''
select @s=@s+', sum(case cid when '+''''+ a.cid+''''+' then score else ''0'' end) as '+''''+a.cid+''''
from ( select distinct cid from tab_score) a
print @*
**ec('select sid'+@s+'from tab_score group by sid')


摘自XX的qq空间
  • 打赏
  • 举报
回复
好象是个面食题?

110,502

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

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