从每个组中选择具有最高价值的记录

时间:2018-07-06 14:47:03

标签: sql sql-server-2012 greatest-n-per-group

假设我有如下表格:

CustomerAdresses表:

Shop        Name        Surname     Adress
----------------------------------------------
SHOP1       name1       surname1    adress1_1 
SHOP2       name1       surname1    adress1_2 
SHOP1       name2       surname2    adress2_1 
SHOP3       name2       surname2    adress2_3 
SHOP3       name1       surname1    adress1_3 

ShopPriority表:

Shop   Priority
---------------
SHOP1       1
SHOP2       2
SHOP3       3

我正在尝试选择具有最高优先级的客户地址(考虑到这是商店)

我写了sql:

select ca.shop, ca.name, ca.surname, ca.adress, sp.priority
from CustomerAdresses ca
join ShopPriority sp on sp.shop = ca.shop
group by ca.name, ca.surname, ca.adress, ca.shop, sp.priority

此查询向我返回如下结果:

Shop        name        surname     adress    priority
-------------------------------------------------------
SHOP1       name1       surname1    adress1_1   1
SHOP2       name1       surname1    adress1_2   2
SHOP3       name1       surname1    adress1_3   3
SHOP1       name2       surname2    adress2_1   1
SHOP3       name2       surname2    adress2_3   3

现在,我已经接近我所需要的。 记录按名称和姓氏分组。现在,我只需要从每个组中获得最高优先级的记录。 分组后我尝试订购记录,但是整个分组都崩溃了

2 个答案:

答案 0 :(得分:1)

您可以使用row_number()函数:

select t.*
from (select ca.shop, ca.name, ca.surname, ca.adress, sp.priority,
             row_number() over (partition by ca.shop order by sp.priority desc) as seq
      from CustomerAdresses ca join 
           ShopPriority sp 
           on sp.shop = ca.shop
      ) t
where seq = 1;

但是,top (1) with ties也很有用:

select top (1) with ties ca.shop, ca.name, ca.surname, ca.adress, sp.priority
from CustomerAdresses ca join 
     ShopPriority sp 
     on sp.shop = ca.shop
order by row_number() over (partition by ca.shop order by sp.priority desc);

答案 1 :(得分:1)

使用ANSI标准的row_number()函数:

select spc.*
from (select ca.shop, ca.name, ca.surname, ca.adress, sp.priority,
             row_number() over (partition by ca.shop order by sp.priority desc) as seqnum
      from CustomerAdresses ca join
           ShopPriority sp
           on sp.shop = ca.shop
     ) spc
where seqnum = 1;