有表
a b
----------------
111 m
111 s
222 i
222 c
222 b
现在我有写一个方法选出这样的数据,
111 m-s
222 i-c-b
就是我选出每一个a对应的b列都一一列出来,中间用横线隔开!
我本来想写个函数
select @b=b where a='111'这样子的.但是好象只能返回一个数据吗?不知道怎么弄了,大家来帮帮我吧
a b
----------------
111 m
111 s
222 i
222 c
222 b
现在我有写一个方法选出这样的数据,
111 m-s
222 i-c-b
就是我选出每一个a对应的b列都一一列出来,中间用横线隔开!
我本来想写个函数
select @b=b where a='111'这样子的.但是好象只能返回一个数据吗?不知道怎么弄了,大家来帮帮我吧
解决方案 »
- 同个表,有数据能select出来,有些数据select不出来
- sql2000 全排列,求和 谢谢
- 求条sql语句!!!!!
- 如何使用sql server客户端工具去连接sqlserver服务器?
- 请问:用 where 子句查询时,设定条件的值与值的数据类型在显示上有哪些语法和需要注意的地方/
- sql server2000中except疑难问题
- 关于查找的问题
- php 异类查询要求为连接设置 ANSI_NULLS 和 ANSI_WARNINGS 选项。这将确保一致的查询语义。请启用这些选项,然后重新发出查询。
- 如何最大提高此储存的执行性能!
- 并发与锁
- 日期SQl
- 如何在SQL SERVER 2000中将系统文件从一个目录移到另一个目录的问题?
insert string select '111', 'm'
union all select '111', 's'
union all select '222', 'i'
union all select '222', 'c'
union all select '222', 'b'
go
create function getString(@s varchar(100))
returns varchar(100)
as
begin
declare @x varchar(100)
select @x=isnull(@x+'-','')+b from string where a=@s
return @x
endgo
select a,dbo.getstring(a) from string group by a
----------------
111 m
111 s
222 i
222 c
222 b
现在我有写一个方法选出这样的数据,
111 m-s
222 i-c-b---------------------
用函數吧可以解決
create function aa(@id varchar(20))
returns varchar(1000)
as
begin
declare @str varchar(1000)
set @str=''
select @str=@str+'-'+b from t where a=@id
return stuff(@str,1,1,'')endselect a,dbo.aa(a) from t
returns varchar(1000)
as
begin
declare @str varchar(1000)
set @str=''
select @str=@str+'-'+b from t where a=@id
return stuff(@str,1,1,'')endselect a,dbo.aa(a) from t group by a
id value
----- ------
1 aa
1 bb
2 aaa
2 bbb
2 ccc需要得到结果:
id values
------ -----------
1 aa,bb
2 aaa,bbb,ccc在SQL Server2000中我们处理的方式一般都是用自定义函数去处理:
举例如下:create function dbo.f_str(@id int)
returns varchar(8000)
as
begin
declare @r varchar(8000)
set @r=''
select @r=@r+','+value from tb where id=@id
return stuff(@r,1,1,'')
end
goselect id, values=dbo.f_str(id) from tb group by id
在SQL Server2005中,这种统计有了一种新的方法,直接使用语句调用sql2005的函数实现:
举例如下:-- 示例数据
DECLARE @t TABLE(id int, value varchar(10))
Insert @t Select 1, 'aa'
UNION ALL Select 1, 'bb'
UNION ALL Select 2, 'aaa'
UNION ALL Select 2, 'bbb'
UNION ALL Select 2, 'ccc'-- 查询处理
Select *
FROM(
Select DISTINCT
id
FROM @t
)A
OUTER APPLY(
Select [values]= STUFF(REPLACE(REPLACE(
(
Select value FROM @t N
Where id = A.id
FOR XML AUTO
), '<N value="', ','), '"/>', ''), 1, 1, '')
)N/*--结果
id values
----------- ----------------
1 aa,bb
2 aaa,bbb,ccc(2 行受影响)
--*/
最近从CSDN上又发现了一种方法!
declare @a varchar(100)
select @a=coalesce(@a+'/','')+PNAME from HPINF where perid like'207%'
select @a