SQL选择三行,同一个表中包含最大行,并与第二个表连接

时间:2017-04-06 13:48:31

标签: sql sql-server

我发现每个合约的最大值atraso,但我也无法提取NUM_PARCELA,仅提取contrato,因为我按contrato分组。
有关每个num_parcela提取max_atrasocontrato的建议吗?

Select  
   a.[CONTRATO]
  ,a.[NUM_PARCELA]
  ,a.[DATA_PAGAMENTO]
  ,a.[DATA_VENCTO]
  ,b.[DATA_LIBER_CONTRATO]
  ,DATEDIFF(day, a.DATA_VENCTO, a.DATA_PAGAMENTO) as ATRASO
 INTO #temp1
  from [fprisco].[dbo].[ParcelasGrc2] as a   
inner join [fprisco].[dbo].[ContratosGrc2] as b     
on b.contrato=a.contrato   
where b.data_liber_contrato >'2017-02-28 00:00:00.000'

Select    
   contrato,   
   max(atraso) as Max_Atraso        
   from #temp1     
group by contrato  
 order by contrato desc 

我需要的是每个atraso的最大contrato,并且num_parcela与最大atraso匹配。 Num_Parcela每个合约都有多条记录,只有一条与最大atraso匹配。

1 个答案:

答案 0 :(得分:0)

如何做到这一点有更多方法,请参阅下面的两个:

测试用例:

DECLARE @temp1 TABLE (contrato int, atraso int, num_parcela int)

INSERT INTO @temp1 VALUES (1,5,1)
INSERT INTO @temp1 VALUES (1,4,2)
INSERT INTO @temp1 VALUES (1,3,3)
INSERT INTO @temp1 VALUES (2,2,1)
INSERT INTO @temp1 VALUES (2,3,1)
INSERT INTO @temp1 VALUES (2,4,2)

第一个使用group by并加入到原始表

的变体
;WITH MaxAtraso AS (
    Select    
       contrato,   
       max(atraso) as Max_Atraso   
    from @temp1     
    group by contrato  
)
SELECT m.*, t.num_parcela FROM MaxAtraso m 
JOIN @temp1 t 
ON m.Max_Atraso = t.atraso AND m.contrato = t.contrato
ORDER BY contrato DESC

使用ROW_NUMBER()的第二个变量变体和有序列表:

;WITH OrderByAtraso AS (
    Select    
       contrato,  
       num_parcela,
       atraso,
       ROW_NUMBER() OVER (PARTITION BY contrato ORDER BY atraso DESC) rn
    from @temp1     
)
SELECT * FROM OrderByAtraso WHERE RN=1 ORDER BY contrato DESC

此外,不需要为此操作创建临时表,您可以像这样重写:

;WITH OrderByAtraso AS (
Select  
   a.[CONTRATO]
  ,a.[NUM_PARCELA]
  ,a.[DATA_PAGAMENTO]
  ,a.[DATA_VENCTO]
  ,b.[DATA_LIBER_CONTRATO]
  ,DATEDIFF(day, a.DATA_VENCTO, a.DATA_PAGAMENTO) as ATRASO
  ,ROW_NUMBER() OVER (
       PARTITION BY contrato 
       ORDER BY DATEDIFF(day, a.DATA_VENCTO, a.DATA_PAGAMENTO) DESC) RN
from [fprisco].[dbo].[ParcelasGrc2] as a   
inner join [fprisco].[dbo].[ContratosGrc2] as b     
on b.contrato=a.contrato   
where b.data_liber_contrato >'20170228'
)
SELECT contrato, atraso as MaxAtraso, num_parcela
FROM OrderByAtraso WHERE RN=1 ORDER BY CONTRATO DESC