0

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

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 函数的长度参数无效。

任何帮助将非常感激

4

2 回答 2

2
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
于 2013-02-28T15:22:29.683 回答
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)
于 2013-02-28T15:26:35.863 回答