表a数据如下:
a b c
1 1 R
1 1 RW
1 1 D
1 2 R
1 2 D
1 3 D
得到的结果:
a b D V
1 1 1 1
1 2 1 1
1 3 0 1规则是:
1,如果A,B相同,当C IN('R','RW') THEN V="1"
当D IN('D') THEN D='1'
2,不要使用游标或是按行处理的方法,因为资料量太大了!
a b c
1 1 R
1 1 RW
1 1 D
1 2 R
1 2 D
1 3 D
得到的结果:
a b D V
1 1 1 1
1 2 1 1
1 3 0 1规则是:
1,如果A,B相同,当C IN('R','RW') THEN V="1"
当D IN('D') THEN D='1'
2,不要使用游标或是按行处理的方法,因为资料量太大了!
解决方案 »
- 昨天去面试,对面非说1000W条数据分页查询要2秒以上,贴测试结果。
- 请问怎样使记录只显示到当前月份
- 存储过程不用参数时能防止SQL注入攻击吗?
- win2003 安装sqlserver 2008
- mssql导入导出数据出错,提示登录‘帐号名’不存在
- 为什么验证登录老是不正确
- sql语句问题?
- 如何实现在一个表中把一个字符字段a和一个字符字段b合成一个字符字段c,然后拷贝到另外一个表中?
- sql server6.5能不能实现触发器与外部程序(如VC++)的通讯
- 关于sql server2000的text类型的使用???
- 我的SQL数据库备份的文件越来越大了,现在有90多兆了,有什么办法压缩一下,或优化一下?
- xp_sendmail提示:没有可用的传输提供商,无法向该收件人传递邮件
A,
B,
max(case when C IN('R','RW') then '1' else '0' end) as V,
max(case when C='D' then '1' else '0' end) as D
from
tName
group by
A,B
那么,如果想要实现这样的结果要怎么做呢?得到的结果:
a b C
1 1 R;RW;D
1 2 R;D
1 3 D
规则:
1,当a,b相同时,将C Columns用';'串起来
2,同样不能使用游标或是按行处理的方法thanks!
from a
bengin
declare @str varchar(8000)
set @str=''
select @str=@str+','+C from TableName where A=@colA and B=@colB
return @str
endselect a,b,dbo.f_str(a,b) as c from TableName group by a,b
create table 表(部门 int,人员 varchar(20))
insert into 表 select 1,'张三'
insert into 表 select 1,'李四'
insert into 表 select 1,'王五'
insert into 表 select 2,'赵六'
insert into 表 select 2,'邓七'
insert into 表 select 2,'刘八'
go--创建用户定义函数
create function f_str(@department int)
returns varchar(8000)
as
begin
declare @ret varchar(8000)
set @ret = ''
select @ret = @ret+','+人员 from 表 where 部门 = @department
set @ret = stuff(@ret,1,1,'')
return @ret
end
go
--执行
select 部门,人员=dbo.f_str(部门) from 表 group by 部门 order by 部门
go--输出结果
/*
部门 人员
---- --------------
1 张三,李四,王五
2 赵六,邓七,刘八
*/
--删除测试数据
drop function f_str
drop table 表
go
bengin
declare @str varchar(8000)
set @str=''
select @str=@str+','+C from TableName where A=@colA and B=@colB
set @str = stuff(@str,1,1,'')
return @str
endselect a,b,dbo.f_str(a,b) as c from TableName group by a,b
returns varchar(100)
as
begin
declare @entry varchar(100)
select @entry=null
select @entry=coalesce(@entry+';','')+c from testA where a= @a and b= @b
return @entry
end
goselect * from testA
select a, b, dbo.addcol(a,b) from testA group by a,b
drop function dbo.addcol