1

例如,假设您有下表

CourseId                             | CourseTitle | EntryMonth | EntryYear |
ebdef239-abb7-4a82-9229-1ed37496da86 | Maths FT    | January    | 2013      |
57504a66-4882-4794-a8b9-af0ead38dc70 | Maths FT    | February   | 2013      |
f06c5e58-5563-4dfd-a8fc-2ce186c2106f | Maths FT    | February   | 2014      |
0c81dfe6-0b11-4cad-a27c-970dbdb2876c | Maths FT    | February   | 2015      |
ebdef239-abb7-4a82-9229-1ed37496da86 | English PT  | January    | 2013      |
57504a66-4882-4794-a8b9-af0ead38dc70 | English PT  | January    | 2014      |

是否可以编写一个按 CourseTitle 和 EntryMonth 分组的查询,但将 EntryYear 值组合到一个临时列中(最好用逗号分隔)。所以它看起来像这样:

CourseId                             | CourseTitle | EntryMonth | NewEntryYear     |
ebdef239-abb7-4a82-9229-1ed37496da86 | Maths FT    | January    | 2013             |
57504a66-4882-4794-a8b9-af0ead38dc70 | Maths FT    | February   | 2013, 2014, 2015 |
ebdef239-abb7-4a82-9229-1ed37496da86 | English PT  | January    | 2013, 2014       |

任何示例将不胜感激。谢谢。

4

2 回答 2

4
select  CourseTitle
,       EntryMonth
,       stuff((
        select  ', ' + cast(EntryYear as varchar)
        from    Table1 t2
        where   t1.CourseTitle = t2.CourseTitle
                and t1.EntryMonth = t2.EntryMonth
        for xml path('')
        ), 1, 2, '') as Years
from    Table1 t1
group by
        CourseTitle
,       EntryMonth

Example at SQL Fiddle.

于 2013-05-03T10:49:05.943 回答
0

如果您使用的是 oracle 10g 或更高版本,以下将起作用:

SELECT COURSEID, COURSETITLE, ENTRYMONTH, 
LISTAGG(ENTRYYEAR, ',') WITHIN GROUP (ORDER BY ENTRYYEAR) AS NEWENTRYYEAR
FROM YOUR_TABLE_NAME 
GROUP BY COURSEID, COURSETITLE, ENTRYMONTH

如果您不使用 Oracle 10g,此查询将没有什么帮助,对此我深表歉意。

于 2013-05-03T10:55:10.850 回答