2013-06-24 28 views
0

我試圖返回狀態列表中的「最大」值。但是,我想爲字符串值指定一個排序值,以便通過我自己的排名返回最大值,而不是按字母順序排列。SQL使用查找來返回組中的最大值?

這裏是我的代碼:

select x.wbs1, x.wbs2, x.wbs3, x.custstatus 
    from (
      select wbs1,wbs2,wbs3,custstatus=MAX(custstatus) 
      from Projects_CRStatus 
      where custsentdate >= 'June 1, 2001' AND custsentdate <= 'June 30, 2013' 
      AND CustStatus IN ('RECEIVED AT VENDOR', 'CONFIRMATION SENT', 
      'IC PENDING','CONFIRMATION RECEIVED','CANCELLED') 
      group by wbs1,wbs2,wbs3) x 
    inner join (
      select wbs1,wbs2,wbs3,custsentdate=max(custsentdate) 
      from Projects_CRStatus 
      group by wbs1,wbs2,wbs3) y 
    on (x.wbs1=y.wbs1 and x.wbs2=y.wbs2 and x.wbs3=y.wbs3) 

    ORDER BY CustEnrollmentID 

我想要做的是排名CustStatus的值,這樣,而不是返回CustStatus的頂部按字母順序排列的結果,我得到了這個秩序的最先進的地位。

  1. '接收的供應商'
  2. '確認書SENT'
  3. 'IC PENDING'
  4. 'CONFIRMATION RECEIVED'
  5. '已取消'
+0

爲了澄清,我正在尋找在x中的每個wbs1,wbs2,wbs3分組內的排名最高的狀態。 –

回答

1

您使用Word 排名,但我猜你真的在問如何訂單您的查詢resul噸。如果是這樣,你可以在ORDER BY子句中使用CASE表達:

ORDER BY CASE WHEN CustStatus = 'RECEIVED AT VENDOR' then 1 
       WHEN CustStatus = 'CONFIRMATION SENT' then 2 
       WHEN CustStatus = 'IC PENDING' then 3 
       WHEN CustStatus = 'CONFIRMATION RECEIVED' then 4 
       WHEN CustStatus = 'CANCELLED' then 5 
       ELSE 6 
     END, CustEnrollmentID 

CASE表達式(在ELSE條件)的最後一項僅僅是爲了安全着想。

更新:根據您的後續意見,這裏是一個查詢返回的「巔峯狀態」使用ROW_NUMBER函數:

select wbs1, wbs2, wbs3, custstatus 

from (
    select x.wbs1, x.wbs2, x.wbs3, x.custstatus, 
     ROW_NUMBER() OVER(PARTITION BY x.wbs1, x.wbs2, x.wbs3 
         ORDER BY CASE 
         WHEN x.CustStatus = 'RECEIVED AT VENDOR' then 1 
         WHEN x.CustStatus = 'CONFIRMATION SENT' then 2 
         WHEN x.CustStatus = 'IC PENDING' then 3 
         WHEN x.CustStatus = 'CONFIRMATION RECEIVED' then 4 
         WHEN x.CustStatus = 'CANCELLED' then 5 
         ELSE 6 END) as rn 
    from (
     select wbs1,wbs2,wbs3,custstatus=MAX(custstatus) 
     from Projects_CRStatus 
     where custsentdate >= 'June 1, 2001' 
     AND custsentdate <= 'June 30, 2013' 
     AND CustStatus IN ('RECEIVED AT VENDOR', 'CONFIRMATION SENT' 
      ,'IC PENDING','CONFIRMATION RECEIVED','CANCELLED') 
     group by wbs1,wbs2,wbs3) x 
    inner join (
     select wbs1,wbs2,wbs3,custsentdate=max(custsentdate) 
     from Projects_CRStatus 
     group by wbs1,wbs2,wbs3) y 
    on (x.wbs1=y.wbs1 and x.wbs2=y.wbs2 and x.wbs3=y.wbs3) 
    ) z 

WHERE RN = 1 
+0

我正在尋找「group by」中的Top狀態結果。所以,我正在尋找每個wbs1,wbs2,wbs3組合的排名最高的狀態。 –

+0

@GabeN。哦。你使用什麼風格的SQL?你熟悉'ROW_NUMBER'窗口函數嗎?如果你的數據庫支持它,那將是一條路。 – BellevueBob

+0

我正在使用SQL Server。我使用了ROW_NUMBER/Partition OVER方法,但獲得了多個結果。 –

0

最好有一個表,這個狀態碼數據,並加入該表,所以將可以通過此狀態表列進行排序。