0

我正在尝试在状态列表中返回“最大值”。但是,我想为字符串值分配一个排序值,以便最大值由我自己的排名返回,而不是按字母顺序。

这是我的代码:

    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. '确认已发送'
  3. 'IC 待定'
  4. '收到确认'
  5. '取消'
4

2 回答 2

1

您使用单词rank,但我猜您确实在询问如何对查询结果进行排序。如果是这样,您可以在子句中使用CASE表达式:ORDER BY

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
于 2013-06-24T16:16:57.067 回答
0

最好有一个包含此状态代码数据的表并连接该表,因此可以按此状态表列进行排序。

于 2013-06-24T16:17:07.413 回答