在SQL Server中连续显示多个记录

时间:2017-12-25 19:02:01

标签: sql sql-server tsql

我在这里发布了一个问题Show multiple records in a row来获得这样的结果

enter image description here

它在MySQL中得到了很好的回答,但我正在使用查询不同的SQL Server。我的桌子是

CREATE TABLE events
(
    id int NOT NULL,
    event_name varchar(100) NOT NULL,
    event_id int NOT NULL
);

INSERT INTO events (id, event_name, event_id)
VALUES (1, 'dance', 1), (2, 'sing', 2), (3, 'acting', 3), (4, 'debate', 4);

CREATE TABLE students 
(
    id int NOT NULL,
    student_name text NOT NULL,
    event_id int NOT NULL
);

INSERT INTO students (id, student_name, event_id)
VALUES (1, 'student1', 1), (2, 'student1', 2),
       (3, 'student1', 3), (4, 'student1', 4),
       (5, 'student2', 3), (6, 'student3', 2),
       (7, 'student3', 4);

我在这里尝试使用示例查询http://rextester.com/RXK72524,但它不能正常工作。

我使用的查询

SELECT 
    s.student_name,
    STUFF (g.student_name, 1, 1, '') AS events
FROM   
    Students s
CROSS APPLY
    (SELECT 
         ',' + e.event_name
     FROM  
         students s
     LEFT JOIN 
         events e ON s.event_id = e.event_id
     ORDER BY 
         e.event_name 
     FOR XML PATH ('')) g (student_name)

请指正。感谢

1 个答案:

答案 0 :(得分:1)

http://rextester.com/LOQZE28952

  

PS:如果将student_name列设为NVACHAR,您的生活会更轻松   而是TEXT

     

它可以帮助您避免使用强制转换功能

--Sql Server 2014 Express Edition
--Batches are separated by 'go'

select @@version as 'sql server version'


CREATE TABLE events (
    id int NOT NULL,
    event_name varchar(100) NOT NULL,
    event_id int NOT NULL
);

INSERT INTO events (id, event_name, event_id)
VALUES
    (1, 'dance', 1),
    (2, 'sing', 2),
    (3, 'acting', 3),
    (4, 'debate', 4);


CREATE TABLE students (
  id int NOT NULL,
  student_name text NOT NULL,
  event_id int NOT NULL
);

INSERT INTO students (id, student_name, event_id)
VALUES
    (1, 'student1', 1),
    (2, 'student1', 2),
    (3, 'student1', 3),
    (4, 'student1', 4),
    (5, 'student2', 3),
    (6, 'student3', 2),
    (7, 'student3', 4);

SELECT DISTINCT(cast(s.student_name as NVARCHAR(100))) as Students,
       stuff (g.student_name, 1, 1, '') as events
FROM   Students s

CROSS APPLY
(
    SELECT ',' + e.event_name
    FROM  Students s1
    left join events e on s1.event_id = e.event_id 
    where cast(s1.student_name as NVARCHAR(100)) = cast(s.student_name as NVARCHAR(100))
    ORDER BY e.event_name 
    FOR XML PATH ('')
) g (student_name)

enter image description here