SQL使用查找返回组中的最大值?

时间:2013-06-24 16:01:09

标签: sql group-by max

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

这是我的代码:

    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. 'CONFIRMATION SENT'
  3. 'IC PENDING'
  4. '确认已收到'
  5. '取消'

2 个答案:

答案 0 :(得分:1)

您使用排名这个词,但我猜您真的在询问如何订购您的查询结果。如果是这样,您可以在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

答案 1 :(得分:0)

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