例如:
表user
userid name
1 张三
2 李四表product
id userid product
1 1 基金
2 1 股票
3 2 基金
我要查询所有用户,但是也要显示产品信息,如下:
1 张三 基金,股票
2 李四 基金应该写一个自定义函数,请教该怎么写,谢谢大家!
表user
userid name
1 张三
2 李四表product
id userid product
1 1 基金
2 1 股票
3 2 基金
我要查询所有用户,但是也要显示产品信息,如下:
1 张三 基金,股票
2 李四 基金应该写一个自定义函数,请教该怎么写,谢谢大家!
解决方案 »
- 如何从int型convert到datetime类型?
- SQL2000升级SQL2005
- 求一条SELECT语句。
- 提问:我的winXP安装sql server时,只能装客户端工具,并且安装以后不能建立数据库,为什么啊?
- 能否给一个简单的作业T-SQL代码:
- 作业权限????
- 如何根据 timestamp 字段查询数据
- 在一个表中有很N个班级(N未知),我需要汇总每个班级总人数,以及每个班状态不为休学学生的总成绩,用一条SQL语句写,该怎么办?
- 在vc中怎么执行ms sql server上的存储过程呢?
- 存储过程的一个问题,高手帮帮忙,分不多了!
- 怎么写出这个我想要的SQL!!!
- 帮忙写几个SQL语句。一小时后结贴。。。
a b
1 1
1 2
1 3
2 1
2 2
3 1
--如何转换成如下结果:
a b
1 1,2,3
2 1,2
3 1 create table tb
(
a int,
b int
)
insert into tb(a,b) values(1,1)
insert into tb(a,b) values(1,2)
insert into tb(a,b) values(1,3)
insert into tb(a,b) values(2,1)
insert into tb(a,b) values(2,2)
insert into tb(a,b) values(3,1)
goif object_id('pubs..f_hb') is not null
drop function f_hb
go--创建一个合并的函数
create function f_hb(@a int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ''
select @str = @str + ',' + cast(b as varchar) from tb where a = @a
set @str = right(@str , len(@str) - 1)
return(@str)
End
go--调用自定义函数得到结果:
select distinct a ,dbo.f_hb(a) as b from tbdrop table tb--结果
a b
----------- ------
1 1,2,3
2 1,2
3 1(所影响的行数为 3 行)
insert into tba values(1, '张三')
insert into tba values(2, '李四')
create table tbb (id int,userid int,product varchar(10))
insert into tbb values(1, 1, '基金')
insert into tbb values(2, 1, '股票')
insert into tbb values(3, 2, '基金')
go
--创建一个合并的函数
create function f_hb(@userid int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ''
select @str = @str + ',' + cast(product as varchar) from tbb where userid = @userid
set @str = right(@str , len(@str) - 1)
return(@str)
End
go--调用自定义函数得到结果:
select tba.*,t.product from tba,
(select distinct userid ,dbo.f_hb(userid) as product from tbb) t
where tba.userid = t.useriddrop table tba,tbb
drop function f_hb/*
userid name product
----------- ---------- -----------
1 张三 基金,股票
2 李四 基金(所影响的行数为 2 行)
*/
表user
userid name
1 张三
2 李四 表product
id userid product
1 1 基金
2 1 股票
3 2 基金
----------------------------
create function wsp(@userid int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
select @str = isnull(@str + ',','') + product from product where userid = @userid
return(@str)
End调用函数:select name,dbo.wsp(userid) from user