SQL Server 2012架构设置:
CREATE TABLE Course
(
CourseID INT IDENTITY(1,1)
,CourseName NVARCHAR(20)
)
CREATE TABLE Session
(
SessionID INT IDENTITY(1,1)
,CourseID INT NULL
)
CREATE TABLE SessionTime
(
,SessionID INT
,DayOfWeek TINYINT --Sunday(0), Monday(1), ..., Saturday(6)
)
INSERT INTO COURSE(CourseName) VALUES('Science 10'), ('Bio 30')
INSERT INTO Session(CourseID) VALUES(1), (2)
INSERT INTO SessionTime(SessionID, DayOfWeek)
VALUES(1, 5), (1, 0), (1, 0), (1, 0), (1, 2), (1, 2), (1, 4),
(2, 1), (2, 3)
查询:
SELECT C.CourseName
,S.SessionID
,STUFF(
(SELECT DISTINCT ', ' + CASE
WHEN ST.DayOfWeek = 0 THEN 'Su'
WHEN ST.DayOfWeek = 1 THEN 'M'
WHEN ST.DayOfWeek = 2 THEN 'T'
WHEN ST.DayOfWeek = 3 THEN 'W'
WHEN ST.DayOfWeek = 4 THEN 'Th'
WHEN ST.DayOfWeek = 5 THEN 'F'
WHEN ST.DayOfWeek = 6 THEN 'Sa'
END
FROM SessionTime ST
WHERE ST.SessionID = S.SessionID
--ORDER BY DayOfWeek
FOR XML PATH (''))
,1,2,'') AS DaysOfWeek
FROM Session S
INNER JOIN Course C on S.CourseID = C.CourseID
| COURSENAME | SESSIONID | DAYSOFWEEK |
|------------|-----------|--------------|
| Science 10 | 1 | F, Su, T, Th |
| Bio 30 | 2 | M, W |
期望的结果:
| COURSENAME | SESSIONID | DAYSOFWEEK |
|------------|-----------|--------------|
| Science 10 | 1 | Su, T, Th, F | *Order of DaysOfWeek has changed.
| Bio 30 | 2 | M, W |
我想在我STUFF
之前订购DayOfWeek(Su,M,T,W,Th,F,Sa),但我的尝试导致了以下错误:
如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。
我尝试过以下方法:
ORDER BY 1
按字母顺序排列日期(Su,M,T,W,Th,F,Sa)ORDER BY DayOfWeek
会产生上述错误消息ORDER BY DayOfWeekCase
将AS DayOfWeekCase
添加到END
的{{1}},但会改变CASE
返回日期的方式如何在FOR XML
之前订购DayOfWeek
?
谢谢!
答案 0 :(得分:1)
请尝试使用DISTINCT
,而不要使用GROUP BY
。然后,您可以ORDER BY DayOfWeek
。
SELECT C.CourseName
,S.SessionID
,STUFF(
(SELECT ', ' + CASE
WHEN ST.DayOfWeek = 0 THEN 'Su'
WHEN ST.DayOfWeek = 1 THEN 'M'
WHEN ST.DayOfWeek = 2 THEN 'T'
WHEN ST.DayOfWeek = 3 THEN 'W'
WHEN ST.DayOfWeek = 4 THEN 'Th'
WHEN ST.DayOfWeek = 5 THEN 'F'
WHEN ST.DayOfWeek = 6 THEN 'Sa'
END
FROM SessionTime ST
WHERE ST.SessionID = S.SessionID
GROUP BY st.DayOfWeek
ORDER BY DayOfWeek
FOR XML PATH (''))
,1,2,'') AS DaysOfWeek
FROM Session S
INNER JOIN Course C on S.CourseID = C.CourseID