将列转换为行,使用分隔符“ - ”,“;”

时间:2013-02-19 13:54:23

标签: sql sql-server sql-server-2008 tsql

输入:

      select(Emp_no, ADate, Atime)

      12333,     12-02-2013,    09.12 - 12.30
      12333,     12-02-2013,    12.32 - 17.30   

      13444,     12-02-2013,    09.10 - 18.30

      14444,     12-02-2013,    09.13 - 12.30
      14444,     12-02-2013,    17.20

输出:

      12333,     12-02-2013,    09.12 - 12.30 ; 12.32 - 17.30
      13444,     12-02-2013,    09.10 - 18.30
      14444,     12-02-2013,    09.13 - 12.30 ; 17.20

1 个答案:

答案 0 :(得分:5)

您可以使用与此类似的内容将多行连接成一行:

select distinct t1.Emp_no,
  t1.ADate, 
  STUFF(
         (SELECT '; ' + cast(t2.Atime as varchar(50))
          FROM yourtable t2
          where t1.Emp_no = t2.Emp_no
            and t1.ADate = t2.ADate
          FOR XML PATH (''))
          , 1, 1, '')  AS Atime
from yourtable t1

请参阅SQL Fiddle with Demo

或者您可以CROSS APPLY使用FOR XML PATH

select distinct t1.Emp_no,
  t1.ADate, 
  left(t2.Atime, len(t2.atime)-1) ATime
from yourtable t1
cross apply
(
  select t2.Atime + '; '
  from yourtable t2
  where t1.Emp_no = t2.Emp_no
    and t1.ADate = t2.ADate
  FOR XML PATH('')
) t2 (Atime)

请参阅SQL Fiddle with Demo