(存储过程)如何排序特殊序列

时间:2017-03-06 07:49:22

标签: sql-server tsql stored-procedures

我有一个问题如何按顺序进行排序

select * from (select @fYear as [Year],
(case when main.Description in ('Kecil', 'Tanah') then 'JK'
 else main.Description
 end) as description,

  --CardType,
  sum(case when MONTH(blue.AppliedDate) = 1 then 1 else 0 end) as Jan_Collection,
  sum(case when MONTH(blue.AppliedDate) = 2 then 1 else 0 end) as Feb_Collection,
 ...

 from tblR as main
 left join tblP as b on  main.requestorid = b.requestorid
 left join tblB as blue on b.partyid = blue.partyid and YEAR(blue.AppliedDate) = @fYear

  group by  (case when description in ('Kecil', 'Tanah') then 'JK'
   else main.Description

端)

  ) t 
 order by (case when t.description =  'Amanah' then 1
                               when t.description = 'Mah' then 2
                               when t.description = 'JK' then 3
                               END) ASC

此输出如下:

enter image description here

需要遵循以下顺序:

enter image description here

我收到此错误:

  

在ORDER BY子句中无效,因为它不包含在   无论是聚合函数还是GROUP BY子句。

谢谢大家。

1 个答案:

答案 0 :(得分:-1)

使用以下查询:

select * from (select @fYear as [Year],
(case when main.Description in ('Kecil', 'Tanah') then 'JK'
     else main.Description
end) as description,

--CardType,
sum(case when MONTH(blue.AppliedDate) = 1 then 1 else 0 end) as Jan_Collection,
sum(case when MONTH(blue.AppliedDate) = 2 then 1 else 0 end) as Feb_Collection,
...

from tblR as main
left join tblP as b on  main.requestorid = b.requestorid
left join tblB as blue on b.partyid = blue.partyid and YEAR(blue.AppliedDate) = @fYear

group by  (case when description in ('Kecil', 'Tanah') then 'JK'
       else main.Description
  end)

) t 
  order by (case when t.description =  'Amanah' then 1
                                   when t.description = 'Mah' then 2
                                   when t.description = 'JK' then 3
                                   END) ASC