在一列中连接多个行

时间:2013-02-28 15:19:39

标签: sql sql-server-2008 concatenation

我有一个产生以下结果的查询

NAME         WeekPattern

John Smith   
John Smith   //
John Smith   OO
Jack Jones   
Jack Jones   O
Jack Jones   //

有没有办法可以连接WeekPattern列,结果会显示如下:

NAME         WeekPattern

John Smith     // OO
Jack Jones     O //

我尝试使用FOR XML PATH但无法使其工作,这是我的尝试查询:

SELECT 
p.p_surname,
p.p_forenames,
LEFT(sr.sr_weekpattern , LEN(sr.sr_weekpattern )-1) AS Weekpattern
FROM 
unitesnapshot.dbo.capd_studentregister sr
INNER JOIN unitesnapshot.dbo.capd_person p ON p.p_id = sr.sr_student
CROSS APPLY
(
    SELECT sr.sr_weekpattern + ' '
    FROM unitesnapshot.dbo.capd_studentregister sr1
    INNER JOIN unitesnapshot.dbo.capd_person p1 ON p1.p_id = sr1.sr_student

    WHERE p.p_id = p1.p_id
    FOR XML PATH('')
) pre_trimmed (Weekpattern)
GROUP BY p.p_surname, p.p_forenames, sr.sr_weekpattern;

运行此查询时出现此错误:

传递给LEFT或SUBSTRING函数的长度参数无效。

非常感谢任何帮助

2 个答案:

答案 0 :(得分:1)

SELECT
     Name,
     STUFF(
         (SELECT ' ' + WeekPattern
          FROM TableName
          WHERE NAME = a.NAME AND WeekPattern IS NOT NULL
          FOR XML PATH (''))
          , 1, 1, '')  AS WeekPatternList
FROM TableName AS a
GROUP BY Name

答案 1 :(得分:1)

根据您现有的查询,您没有引用LEFT中正确的列,您应该使用:

SELECT 
  p.p_surname,
  p.p_forenames,
  LEFT(pre_trimmed.Weekpattern , LEN(pre_trimmed.Weekpattern)-1) AS Weekpattern
FROM unitesnapshot.dbo.capd_studentregister sr
INNER JOIN unitesnapshot.dbo.capd_person p 
  ON p.p_id = sr.sr_student
CROSS APPLY
(
  SELECT sr1.sr_weekpattern + ' '
  FROM unitesnapshot.dbo.capd_studentregister sr1
  INNER JOIN unitesnapshot.dbo.capd_person p1 
    ON p1.p_id = sr1.sr_student
  WHERE p.p_id = p1.p_id
  FOR XML PATH('')
) pre_trimmed (Weekpattern)