如何选择3次出现的记录,并将多行组合成sql server 2005中逗号分隔的列表

时间:2012-03-01 09:02:24

标签: sql sql-server-2005

这是我的表

create table student
(
stu_id int,
s_name nvarchar(max),
s_subject nvarchar(max),
marks int
)

和行是 -

stu_id  s_name  s_subject   marks
123 Sam English     86
123 Sam Maths       93
123 Sam Chemistry   85
124 Emma    Biology     80
125 Abbey   Physics     90
125 Abbey   Computer    95
125 Abbey   ED      75

我想要出现两次以上的学生。

我想要这个:

stu_id  s_name  s_subject                marks
123 Sam English,Maths,Chemistry      86,93,85               
125 Abbey   Physics,Computer,ED      90,95,75

我所做的是

DECLARE @sub_list AS varchar(MAX) -- Leave as NULL
DECLARE @marks_list AS varchar(MAX)

SELECT @sub_list = COALESCE(@sub_list + ',', '') + CONVERT(varchar, s_subject),
@marks_list = COALESCE(@marks_list + ',', '') + CONVERT(varchar, marks)

FROM student where stu_id in (
    select stu_id 
    from student
    group by stu_id
    having count(stu_id) > 2
) 
select @sub_list as Subject_ ,@marks_list as Marks;

我的结果很糟糕。

Subject_                    Marks
English,Maths,Chemistry,Physics,Computer,ED 86,93,85,90,95,75

请帮助我从早上开始尝试....

2 个答案:

答案 0 :(得分:2)

希望这个例子有用:

DECLARE @people TABLE(id INT, NAME NVARCHAR(MAX))

INSERT @people VALUES (1, 'John'), (2, 'Mary')

DECLARE @cars TABLE(ownerId INT, NAME NVARCHAR(MAX))

INSERT @cars VALUES (1, 'Toyota'), (1, 'Lada'), (2, 'Nissan'), (2, 'Mazda'), (2, 'Buick')

SELECT 
    Id,
    Name,
    STUFF((
        SELECT ','+name
        FROM @Cars c
        WHERE c.OwnerId = p.Id
        FOR XML PATH('')
    ),1,1,'') AS OwnedCars
FROM @people p

关于您的案例:

;WITH Students(Id, Name) AS
(
    SELECT DISTINCT stu_id, s_name
    FROM Student
)

SELECT
    Id,
    Name,
    STUFF((
        SELECT ','+s_subject
        FROM student
        WHERE student.stu_id = Students.Id
        FOR XML PATH('')
    ),1,1,'') AS s_subjects,
    STUFF((
        SELECT ','+CAST(marks AS varchar)
        FROM student
        WHERE student.stu_id = Students.Id
        FOR XML PATH('')
    ),1,1,'') AS marks
FROM Students 

答案 1 :(得分:2)

select S1.stu_id,
       S1.s_name,
       stuff((select ','+S2.s_subject
              from student as S2
              where S2.stu_id = S1.stu_id
              for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') as s_subject,
       stuff((select ','+cast(S2.marks as varchar(max))
              from student as S2
              where S2.stu_id = S1.stu_id
              for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') as marks
from student as S1
group by S1.stu_id, S1.s_name
having count(*) >= 3

试试SE-Data