为 MAX() SQL SERVER- Row_number() 挑选各自的 serviceID?

Picking out respective serviceID for MAX() SQL SERVER- Row_number()?

我需要有关我正在处理的问题的指导,但我以前没有解决它的经验。

基本上,数据是这样的:

Customer Nr Service ID  Months left till  service expiry
57833357    149080495                   0
57624280    141110847                   0
57885974    149080449                   0
57885974    149080480                   7
57885974    149080499                   1

场景:

我试图找出“Months left till service expiry”列的 MAX(),每个 Customer Nr

要求:

我基本上要寻找的是,在为每个客户 Nr 选择 MAX() 时,还要为 returns MAX(Months left till service expiry) 的列选择相应的 service ID

比如上面的数据中,customer nr =57885974在不同的服务ID:s上出现了3次。 service ID=149080480 距离到期还有 7 个月,这是客户编号 :57885974 的 MAX()。

如何才能只使用 Customer Nr、服务 ID(服务到期前的 MAX() 个月)和服务到期前的几个月?

示例如下:

Customer Nr Service ID  Months left till  service expiry
57833357    149080495           0
57624280    141110847           0
57885974    149080480           7

我的代码目前是这样的:

SELECT DISTINCT

Customer_nr,
[Months left till service expiry]=CASE WHEN DATEDIFF(DAY,Date,EndDate) BETWEEN 0 AND 30 THEN '1'
 WHEN DATEDIFF(DAY,Date,EndDate) BETWEEN  31 AND 60 THEN '2'
ELSE SOMETHING END

FROM TABLE A
GROUP BY Customer_nr,
serviceID,
CASE WHEN DATEDIFF(DAY,Date,EndDate) BETWEEN 0 AND 30 THEN '1'
 WHEN DATEDIFF(DAY,Date,EndDate) BETWEEN  31 AND 60 THEN '2'
ELSE SOMETHING END

在接下来的 table 中,我简单地使用 Customer_nr 和 MAX([剩余月数直到服务到期])进行分组,它就起作用了。但是,我还需要相应的 serviceID.

我该怎么做?

你可以直接使用 row_number():

select a.*
from (select a.*,
             row_number() over (partition by Customer_nr order by [Months left till service expiry] desc) as seqnum
      from a
     ) a
where seqnum = 1;

因为可以使用 Sql CTE expression 构建类似的解决方案 在 Select 查询

中使用 SQL 服务器排名函数和分区依据是此类过滤的主要解决方案
/*
create table tblExp (CustomerNr int, ServiceID  int, MonthsForExpiry int)
insert into tblExp select 57833357    ,149080495                   ,0
insert into tblExp select 57624280    ,141110847                   ,0
insert into tblExp select 57885974    ,149080449                   ,0
insert into tblExp select 57885974    ,149080480                   ,7
insert into tblExp select 57885974    ,149080499                   ,1
*/
;with cte as (
    select *,
    rn = ROW_NUMBER() OVER (Partition by CustomerNr Order By MonthsForExpiry desc)
    from tblExp
)
select * from cte where rn = 1