如果两个记录在SQL Server中的组中具有相同的排名,如何在每个组中对记录进行排名并检查其他变量以分配等级?

时间:2019-04-14 16:38:57

标签: sql sql-server

我有一个数据集,该数据集基本上可以告诉您为每个零售商发送了多少张优惠券,以及有多少回复,对每个经销商和每个优惠券的相应回复率。

我希望根据响应率对每个经销商中的每个优惠券进行排名,如果两个优惠券具有相同的响应率,那么我需要为发送最多的优惠券分配更好的排名

这是我尝试过的脚本,但是排名不正确

SELECT 
    DealerCode, Coupon_name, emailsent, responders, responserate,
    RN = RANK() OVER (PARTITION BY DealerCode, Coupon_name, responserate
                      ORDER BY DealerCode, responserate, emailsent)
FROM 
    table123 

这是预期的结果

RetailerCode    Coupon_name emailsent   responders  responserate    RN
----------------------------------------------------------------------
A1                Coupon 1     6              1     0.166666667      1
A1                Coupon 2     10             1     0.1              2
A1                Coupon 7     50             2     0.04             3
A1                Coupon 9     25             1     0.04             4
A2                Coupon 1     28             3     0.10714          2
A2                Coupon 4     12             0     0                3
A2                Coupon 3     1217           131   0.1076           1
A3                Coupon 2     63             10    0.1587           1
A3                Coupon 6     9              1     0.11111          2
A3                Coupon 7     3              0     0                3
A3                Coupon 8     2              0     0                4
A4                Coupon 4     174            22    0.1266782        3
A4                Coupon 3     1118           244   0.2182869        1
A4                Coupon 6     3091           420   0.135877         2
A5                Coupon 3     1227           78    0.06356962       2
A5                Coupon 2     780            50    0.064104         1
A5                Coupon 1     164            6     0.0365866        3

3 个答案:

答案 0 :(得分:0)

听起来像您想要PARTITION BYdealercodecoupon_nameORDER BY的{​​{1}}({发送优惠券的编号)都降序。

responserate

答案 1 :(得分:0)

使用row_number

SELECT dealercode,
       coupon_name,
       emailsent,
       responders,
       responserate,
       row_number() OVER (PARTITION BY dealercode,
                                      coupon_name
                         ORDER BY responserate DESC,
                                    emailsent desc
                                  ) RN
       FROM table123;

答案 2 :(得分:0)

对于您的示例,您应该仅使用PARTITION BY DealerCode

  SELECT DealerCode, Coupon_name, emailsent, responders, responserate,
   RN = RANK()OVER(PARTITION BY DealerCode
   ORDER BY DealerCode,responserate,emailsent)
  FROM table123