我发现每个合约的最大值atraso
,但我也无法提取NUM_PARCELA
,仅提取contrato
,因为我按contrato
分组。
有关每个num_parcela
提取max_atraso
,contrato
的建议吗?
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
匹配。
答案 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