SQL 經典實例

declare @users table( userid int, username varchar(10),usertel varchar(20))
insert into @users select 8001, 'jacky','131000000'
union all select 8002,'Fiona','132000000'
union all select 8003,'steven','133000000'
declare @avters table (userid int,num int)
insert into @avters select 8001,100
union all select 8003,200
union all select 8003,60
union all select 8002,30
union all select 8001,100
union all select 8002,80
SELECT A.userid,A.userName,A.userTel, SUM(ISNULL(B.num,0)) AS sum_num FROM @users AS A right JOIN @avters AS B ON A.userid=B.userid
GROUP BY A.userid,A.userName,A.userTel
 
declare @t table (userid int,num int)
insert into @t select
create function dbo.fun_str(@id int) returns varchar(8000) as
begin
 declare @r varchar(8000)
 set @r=''
 select @r=@r+','+numbers
 from tb
 where id=@id
 return stuff(@r,1,1,'')
end
select id ,numbers=dbo.fun_str(id) from tb  group by id
declare @t table(id int, numbers varchar(10))
insert @t select 1,'aa'
union all select 1,'a'
union all select 1,'aaa'
union all select 2,'b'
union all select 2,'bb'
union all select 2,'bbb'
select *
FROM(
    SELECT DISTINCT
        id
    FROM tb
)A
OUTER APPLY(
    SELECT
        [numbers]= STUFF(REPLACE(REPLACE((SELECT numbers FROM tb N WHERE id = A.id FOR XML AUTO), '<N numbers="', ','), '"/>', ''), 1, 1, '')
)N
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章