您好我正在使用此查询来制作事件列表
SELECT *, CASE
WHEN ((month > 9 OR (month =9 and days >= 22)) AND year <= 2012)then 'list1'
WHEN (year <= 2013) then 'list2'
WHEN (year > 2013)then 'list3'
end as sortlist from events order by sortlist, date
现在我想按同一个sql对list3进行排序,按年份排序。这可能吗?
答案 0 :(得分:1)
如果您有SQL SERVER 2005或更高版本,则可以执行此操作
SELECT
*,
CALC.sortlist
from events as e
outer apply
(
select
case
WHEN ((e.month > 9 OR (e.month =9 and e.days >= 22)) AND e.year <= 2012)then 'list1'
WHEN (e.year <= 2013) then 'list2'
WHEN (e.year > 2013)then 'list3'
end as sortlist
) as CALC
order by
CALC.sortlist, CALC.date,
case when CALC.sortlist = 'list3' then e.year else null end
你也可以这样做,但如果你的情况相同,那么它并不完全按年份排序&#39; list3&#39; (我的意思是,如果您要更改case
中的表达式,您还需要更改order by
SELECT
*,
case
WHEN ((e.month > 9 OR (e.month =9 and e.days >= 22)) AND e.year <= 2012)then 'list1'
WHEN (e.year <= 2013) then 'list2'
WHEN (e.year > 2013)then 'list3'
end as sortlist
from events as e
order by
sortlist, e.date,
case when e.year > 2013 then e.year else null end
答案 1 :(得分:0)
我得到了解决方案。 按顺序,我刚编辑为
order by sortlist, case when sortlist='list3' then year else null end,