我有一个表,该表的一列中有多个值。我需要为每个值创建单独的行。我不知道该如何处理。我可以用逗号分隔列中的值,但此后我迷路了。欢迎任何建议。
表 课程
Name | Courses
--------------------------
Kyle | Math, English, Science
Joe | Math, English
结果表
Name | Courses
-----------------------------
Kyle | Math
Kyle | English
Kyle | Science
Joe | Math
Joe | English
答案 0 :(得分:0)
试试这个-
从-Here
获得的帮助;WITH CTE (Name,Courses)
AS
(
SELECT Name,Courses FROM Courses
),
tmp(Name, DataItem, Courses)
AS
(
SELECT
Name,
CAST(LEFT(Courses, CHARINDEX(',', Courses + ',') - 1) AS VARCHAR),
STUFF(Courses, 1, CHARINDEX(',', Courses + ','), '')
FROM CTE
UNION all
SELECT
Name,
CAST(LEFT(Courses, CHARINDEX(',', Courses + ',') - 1) AS VARCHAR),
STUFF(Courses, 1, CHARINDEX(',', Courses + ','), '')
FROM tmp
WHERE
Courses > ''
)
SELECT
Name,LTRIM(RTRIM(DataItem)) Course
FROM tmp
ORDER BY Name