有没有简单的语句返回前几条id加逗号合并成的字符串呀
比如 select top 5 id from table order by id desc前五条id分别为为
16
15
14
13
12
要求返回 '16,15,14,13,12'这样的字符串
不要用游标的,先谢了
比如 select top 5 id from table order by id desc前五条id分别为为
16
15
14
13
12
要求返回 '16,15,14,13,12'这样的字符串
不要用游标的,先谢了
描述:将如下形式的数据按id字段合并value字段。
id value
----- ------
1 aa
1 bb
2 aaa
2 bbb
2 ccc
需要得到结果:
id value
------ -----------
1 aa,bb
2 aaa,bbb,ccc
即:group by id, 求 value 的和(字符串相加)
*/
--1、sql2000中只能用自定义的函数解决
create table tb(id int, value varchar(10))
insert into tb values(1, 'aa')
insert into tb values(1, 'bb')
insert into tb values(2, 'aaa')
insert into tb values(2, 'bbb')
insert into tb values(2, 'ccc')
gocreate function dbo.f_str(@id int) returns varchar(100)
as
begin
declare @str varchar(1000)
set @str = ''
select @str = @str + ',' + cast(value as varchar) from tb where id = @id
set @str = right(@str , len(@str) - 1)
return @str
end
go--调用函数
select id , value = dbo.f_str(id) from tb group by iddrop function dbo.f_str
drop table tb
DECLARE @STR VARCHAR(8000)SELECT @STR=ISNULL(@STR+',','')+CONVERNT(VARCHAR,ID) FROM TBSELECT @STR
set @s=''
select @s=@s+','+quotename([id])+'=max(case when [id]='+quotename([id],'''')+' then [id] else 0 end)' from tb select stuff(@s,1,',','')
declare @s varchar(8000)
set @s=''
select @s=@s+','+cast([ID] as varchar(10)) from tbselect stuff(@s,1,1,'')/*
1,2,3,4,5,6,7,8,9,10,11,12,13(所影响的行数为 1 行)*/
CREATE TABLE TBTEST(ID INT IDENTITY(1,1),NUM INT)
INSERT TBTEST
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7
DECLARE @STR VARCHAR(8000)SELECT @STR=ISNULL(@STR+',','')+CONVERT(VARCHAR,ID) FROM (SELECT TOP 5 ID FROM TBTEST ORDER BY ID DESC)AS TSELECT @STR7,6,5,4,3(所影响的行数为 1 行)
insert @T
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9 union all
select 10 union all
select 11 union all
select 12 union all
select 13 union all
select 14 union all
select 15 union all
select 16 union all
select 17 union all
select 18
select value= stuff((select ','+cast(id as varchar(10)) from (select top 5 * from @T order by Id DESC)T for xml path('')),1,1,'')
/*
18,17,16,15,14
*/