Metal帮助我编写了如下的SQL
select id
, OrderDate
, RejectDate
, max(case when RejectDate = '1900-01-01' then '9999-12-31' else RejectDate end) as rSum
from tableA
group by id, OrderDate, RejectDate
现在,我想找出低于最大拒绝日期的特定ID的所有记录,以将它们从转换表中删除
答案 0 :(得分:1)
一种选择是使用row_number()
:
select
id,
OrderDate,
RejectDate
from (
select
t.*,
row_number() over(
partition by id
order by case when RejectDate = '1900-01-01' then '9999-12-31' else RejectDate end desc
) rn
from tableA t
) t
where rn > 1
该技术的优势在于它避免了聚合,而聚合可能会导致更好的性能。另外,您可以利用可更新CTE的概念轻松地将其转换为delete
语句,如下所示:
with cte as (
select
row_number() over(
partition by id
order by case when RejectDate = '1900-01-01' then '9999-12-31' else RejectDate end desc
) rn
from tableA t
)
delete from cte where rn > 1
答案 1 :(得分:0)
这应该有效...
SELECT *
FROM tableA t1
INNER JOIN (
SELECT ID, MAX(RejectDate) as MaxRejectDate
FROM tableA) t2 ON t1.ID = t2.ID
WHERE t1.RejectDate < t2.MaxRejectDate