我有以下查询返回基于con CBU和DATE(Fecha)的数据订单集
SELECT
cta.CODIGO, cta.cbu, cta.fecha
FROM
CUENTA_BANCARIA as CTA
WHERE
(CTA.ESTADO = 1) and (CTA.HABILITADA = 1)
AND EXISTS (SELECT C.*
FROM CUENTA_BANCARIA as C
WHERE (C.CODIGO != CTA.CODIGO)
AND (C.NRO_CTA = CTA.NRO_CTA)
AND (C.CBU = CTA.CBU)
AND (C.ESTADO = 1)
AND (C.HABILITADA = 1))
ORDER BY
CTA.CBU, CTA.FECHA DESC
我需要使用没有最新DATE(FECHA)的相同CBU更新任何CUENTA_BANCARIA
例如,对于给定的结果,我需要使用以橙色突出显示的codigo更新CUENTA_BANCARIA,因为它们都具有相同的CBU但是较旧的DATE(FECHA)
如何创建此类查询?
答案 0 :(得分:0)
关于RowNumber
及Partition By
@pmbAustin消息,这是解决方案
update cb
set cb.HABILITADA = 0
from CUENTA_BANCARIA cb
where cb.codigo in (
select SubQuery.codigo
(SELECT cta.CODIGO, cta.NRO_CTA, cta.cbu, cta.fecha, ROW_NUMBER() over (PARTITION BY CTA.cbu order by CTA.fecha desc) as numRepetido
from CUENTA_BANCARIA as CTA
where
(CTA.ESTADO = 1) and (CTA.HABILITADA = 1)
and
exists (SELECT C.* FROM CUENTA_BANCARIA as C where (C.CODIGO != CTA.CODIGO) and (C.NRO_CTA = CTA.NRO_CTA) and (C.CBU = CTA.CBU) and (C.ESTADO = 1) and (C.HABILITADA = 1))) as SubQuery
where SubQuery.numRepetido != 1)