为MAX()SQL SERVER- Row_number()挑选相应的serviceID?

时间:2015-07-07 11:10:13

标签: sql 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

情景:

我想找出MAX()" Months left till service expiry"列,每个Customer Nr

要求:

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

例如,在上面的数据中,customer nr = 57885974在不同的服务ID上出现三次:s。 service ID = 149080480还剩7个月到期,这是客户的MAX():57885974。

怎么能这样做只需要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

在下一个表格中,我只使用Customer_nr和MAX([剩余几个月到服务到期])进行分组,然后就可以了。但是,我还需要相应的serviceID

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用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;

答案 1 :(得分:1)

可以使用Sql CTE expression构建类似的解决方案 使用带有分区依据的SQL Server排名功能是选择查询中此类过滤的主要解决方案

/*
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