多行数据转化为一行

来源:互联网 发布:.ga域名是哪的 编辑:程序博客网 时间:2024/06/06 07:03

写一Function

alter   function   f_hb(@id   int)
returns   varchar(8000)
as
begin
    declare   @str   varchar(8000)
    set   @str   =   ' '
    select   @str   =   @str   +   ','   +   cast(stime   as   varchar)   from   s   where   tid   =   @id
    set   @str   =   right(@str   ,   len(@str)   -   1)
    return(@str)
End

其中 stime 是你需要相加 的字段

tid 是你的外键

s 为你的次表

 


select   t.tid ,  max(ss)  from   s,
(select   distinct   tid   ,dbo.f_hb(t.tid)   as   ss   from  t)   t
where   s.tid   =   t.tid
group by t.tid

 

t 为主表

原创粉丝点击