我正在使用SQL Server 2012。
这是我的查询,我希望按此顺序排序,而不是按字母顺序排列。
这是我想要的顺序:
Foreign,
Out of State,
Texas,
Unknown,
Total Enrollment
我按案例使用了顺序,但是我收到了错误:
' 5'
附近的语法不正确
我该如何解决?
查询:
declare @Term int = 20172;
select
[Category], [Last_Term], [Current_Term], [#Change], [%Change]
from
(select
[Category],
cast(round(((cast(y.Last_Term as float)) * 1), 2) as varchar(10)) as 'Last_Term',
cast(round(((cast(y.Current_Term as float)) * 1), 2) as varchar(10)) as 'Current_Term',
cast(round(((cast(y.Current_Term as float) -
cast(y.Last_Term as float)) * 1), 2) as varchar(10)) as '#Change',
cast(round((((cast(y.Current_Term as float) -
cast(y.Last_Term as float)) /
(cast(y.Last_Term as float))) * 100), 2) as varchar(10)) + '%' as '%Change'
from
(select
Category,
Case
when year = substring(CAST (@Term- 10 as Varchar(10)),1,4)
then 'Current_Term'
when year = substring(CAST (@Term - 20 as Varchar(10)),1,4)
then 'Last_Term'
End As ACAD_YEAR,
a.enroll
from
(select
case
when dh.HOME = 'F'
then 'Foreign'
when dh.HOME = 'O'
then 'Out of State'
when dh.Home = 'I'
then 'texas'
when dh.Home = 'U'
then 'UnKnown'
end as Category,
(CONVERT(INT, SUBSTRING(ACADEMIC_PERIOD, 1, 4))) - 1 as year,
count(*) as enroll
from
[IR_DW].[dbo].[dw_enrollment_F] d
inner join
dim_Time t on d.TIME_KEY = t.TIME_KEY
inner join
dim_Home dh on d.HOME_KEY = dh.HOME_KEY
inner join
dim_Student_Level sl on d.STUDENT_LEVEL_KEY = sl.STUDENT_LEVEL_KEY
where
ACADEMIC_PERIOD_ALL = @Term - 10
or ACADEMIC_PERIOD_ALL = @Term
group by
dh.HOME, (CONVERT(INT,SUBSTRING(ACADEMIC_PERIOD,1,4))) - 1) a
) src
PIVOT
(SUM(Enroll) FOR ACAD_YEAR in ([Current_Term] , [Last_Term])) y
) a
order by
case
when a.[Category] = 'Foreign' then 1
when a.[Category] = 'Out of State' then 2
when a.[Category] = 'Texas' then 3
when a.[Category] = 'Unknown' then 4
答案 0 :(得分:2)
虽然您错过了END
案例,但您遗失了5
when a.[Category] = 'Total Enrollment' then 5
ORDER BY
case when a.[Category] = 'Foreign' then 1
when a.[Category] = 'Out of State' then 2
when a.[Category] = 'Texas' then 3
when a.[Category] = 'Unknown' then 4
when a.[Category] = 'Total Enrollment' then 5 --added this
else 6 --catch all to make anything that fell outside of these categories unsorted afterwards
end --added here