2011-08-05 76 views
3
select 
     case status 
      when 'AR' then 1 
      when 'AV' then 2 
      when 'AN' then 3 
      when 'AD' then 4 
      when 'AC' then 5 
      when 'AY' then 6 
      when 'AH' then 7 
      else 8 
     end 'status_order', COUNT(*) 
from dn_appeal_request 
group by 
     case status 
      when 'AR' then 1 
      when 'AV' then 2 
      when 'AN' then 3 
      when 'AD' then 4 
      when 'AC' then 5 
      when 'AY' then 6 
      when 'AH' then 7 
      else 8 
     end 

有沒有辦法通過在select中使用相同的case語句來做一個組?按問題分組

回答

1

可避免使用子查詢重複你的case語句。你確實需要對價值進行分組。

select D.status_order, COUNT(*) 
from (
     select case status 
       when 'AR' then 1 
       when 'AV' then 2 
       when 'AN' then 3 
       when 'AD' then 4 
       when 'AC' then 5 
       when 'AY' then 6 
       when 'AH' then 7 
       else 8 
       end 'status_order' 
     from dn_appeal_request 
    ) as D 
group by D.status_order 
+0

感謝的Mikael多行.. –

0

不,在上面的示例中,沒有辦法避免GROUP BY子句中的CASE。

如果你絕對不想重複自己,你可以做一個解決辦法是建立一個派生表:

SELECT CASE [Status] when 'AR' then 1    
     when 'AV' then 2    
     when 'AN' then 3    
     when 'AD' then 4    
     when 'AC' then 5    
     when 'AY' then 6    
     when 'AH' then 7    
     else 8   
     END AS status_order 
     ,Total 
FROM (
    SELECT [Status], COUNT(*) AS Total 
    FROM dn_appeal_request 
    GROUP BY [Status] 
) AS Foo 
+0

如果有不被抓住了不止一個值'when'你將有'status' 8 –