SQL删除基于多列的行

时间:2016-03-08 18:26:42

标签: sql conditional sql-delete delete-row

我有一个包含8个列的表,包括设备ID,设备读取类型和设备读取日期。这三列看起来像这样: Example Table

我想要做的是删除DevReadType = XX的每一行以及具有匹配DevNum的每一行但DevReadDate小于DevReadType =' XX'的日期。我还没有能够找到这种复杂条件的任何例子。非常感谢帮助!!

2 个答案:

答案 0 :(得分:0)

delete from device
   where  DevNum = @devicenum
   and    DevReadType = 'XX'
   and    DevReadDate < @date

你可以先运行select againsr设备表来测试你的where子句:

select * 
from device
    where  DevNum = @devicenum
    and    DevReadType = 'XX'
    and    DevReadDate < @date

答案 1 :(得分:0)

如果我理解正确,我会提出以下建议:

DELETE  d
FROM device d
JOIN (
    SELECT DevNum, MAX(DevReadDate) maxDevReadDate
    FROM device
    WHERE devReadType = 'xx'
    GROUP BY DevNum
) b
ON d.DevNum = b.DevNum AND (d.DevReadDate < b.maxDevReadDate OR d.devReadType = 'xx')