我需要帮助来构建特定查询。
方案
我有一个带有pol_id(auto_incremente)的表A,someOtherID和someValue
表的内容可能如下所示:
pol_id, someOtherID, someValue -------------------------------- 1 5005 I Like cheeseburger 2 5005 I Like Bananas 3 6000 In Toronto 4 6018 Open the door 5 6018 Really 6 6018 French Fries
有第三方软件,它从该表中收集数据。我对操作软件使用的sql语句没有任何影响,因为我无法访问它的源代码。
第三方软件使用'someOtherID'选择所有内容,例如6018,所以它显示3个结果。问题是,我只想显示最后一个结果(具有最高的pol_id)。所以我想我会做一个cronjob或者做以下事情的事情:
选择每个唯一的someOtherIDs降序, 删除该表中的所有内容,其中someOtherID等于所选的一个和不同的pol_id
类似的东西:
pseudocode: select distinct someOtherID, pol_id from A order by pol_id DESC --to get the highest one for each someOtherID as selectedLine: delete from A where someOtherID = selectedLine.someOtherID AND pol_id != selectedLine.pol_id
我想每隔几秒钟运行一次这个陈述,或者把它放在一个触发器上,以便表A总是干净的
修改 我从达米恩那里寻求触发解决方案,谢谢大家的回应。
答案 0 :(得分:1)
;WITH a as
(
SELECT row_number() over (partition by someOtherID order by pol_id desc) rn
FROM tableA
)
DELETE FROM a where rn > 1
答案 1 :(得分:1)
如果您对触发器感到满意:
CREATE TRIGGER T_TableA_I
on TableA
after insert
as
set nocount on
delete from a
from
TableA a
inner join
(select someOtherID,MAX(pol_id) as maxPol from inserted
group by someOtherID) b
on
a.someOtherID = b.SomeOtherID and
a.pol_id < maxPol
即使包含两行或多行具有相同someOtherID
答案 2 :(得分:1)
delete from t where
exists (select 1 from t t1
where t1.someOtherID=t.someOtherID
and t1.pol_id>t.pol_id)
答案 3 :(得分:0)
你可以试试这个 删除A其中someOtherID ='6018'且pol_id不在( 从A中选择Max(Pol_id),其中someOtherID ='6018');