gpt4 book ai didi

sql - 按 XML 的不同大小写排序

转载 作者:行者123 更新时间:2023-12-05 05:26:02 25 4
gpt4 key购买 nike

SQL Fiddle

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

Results :

| 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 |

我想在将 DayOfWeek (Su,M,T,W,Th,F,Sa) STUFF 全部放在一起之前订购它们,但我的尝试导致了以下错误:

ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

我试过以下方法:

  • ORDER BY 1 按字母顺序排列日期,而不是 (Su,M,T,W,Th,F,Sa)
  • ORDER BY DayOfWeek 导致上述错误消息
  • ORDER BY DayOfWeekCase 添加一个 AS DayOfWeekCaseCASEEND 但这改变了方式 FOR XML 返回天数

如何在 STUFF 合并之前订购 DayOfWeek

谢谢!

最佳答案

不要使用 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

关于sql - 按 XML 的不同大小写排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28848566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com