如何从子查询中获取多个值?

时间:2017-06-29 05:59:51

标签: sql sql-server

我有2个结果集:

result_1:

| reportCard | exam | lessonType | lesson |
|------------|------|------------|--------|
|reportCard_1|exam_1|lessonType_1|lesson_1|
|reportCard_1|exam_2|lessonType_1|lesson_2|
|reportCard_1|exam_3|lessonType_1|lesson_3|
|reportCard_1|exam_4|lessonType_1|lesson_4|

result_2:

| reportCard | lessonType |
|------------|------------|
|reportCard_1|lessonType_1|
|reportCard_1|lessonType_2|

现在我需要这个结果作为文本:

  

lessonType_1; lesson_1 ... lesson_2 ... lesson_3 ... lesson_4 ...

     

lessonType_2; lesson_1 ... lesson_2 ... lesson_3 ... lesson_4 ...

因为课程不仅仅是课程类型而且课程取决于课程类型我使用的子查询是这样的:

select lessonType.title+
       char(10)+
       (
        select lesson.title'+...
        from
        ...
       )
from
...

遗憾的是发生了这个错误:

Msg 512, Level 16, State 1, Line 8
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

但实际上我需要我的子查询返回多个值。 有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您似乎正在寻找给定课程类型中每课的一些组连接。 SQL Server没有像MySQL这样的GROUP_CONCAT()函数,但你可以使用STUFF()来模拟它:

SELECT
    t1.lessonType,
    STUFF((
          SELECT ',' + t2.lesson
          FROM yourTable t2
          WHERE t1.lessonType = t2.lessonType
          FOR XML PATH('')), 1, 1, '') AS lessonText
FROM yourTable t1
GROUP BY
    t1.lessonType

Demo