表名Queue_Demo
SnipID UserID
AAQXFU 179
AAQXFU 161
AAQXFU 164
AATEGD 161
AATEGD 164
AATEGD 179
AATSIE 179
AATSIE 161
AATSIE 164
如果UserID
例如179
来问SnipID
,他会得到AAQXFU
因此,应从Queue_Demo
表中删除SnipID
。
我的Get
方法
set nocount on;
with cte as (
select top(1) SnipID
from dbDataEntry.Queue_Demo with (rowlock, readpast)
where UserID =179
order by SnipID
)
delete from cte
output deleted.SnipID;
此方法仅用UserID
179
删除一行。
但是带有AAQXFU
的另一行仍然在那里。
编辑:
我想要的是。是要删除AAQXFU
答案 0 :(得分:1)
您也可以这样做
set nocount on;
with cte as (
select top(1) SnipID
from dbDataEntry.Queue_Demo with (rowlock, readpast)
where UserID =179
order by SnipID
)
delete a output DELETED.snipid from dbDataEntry.Queue_Demo a
inner join cte b on a.snipid = b.snipid
编辑-将输出添加到查询
答案 1 :(得分:1)
使用您的测试数据,这会删除SnipID等于AAQXFU的所有行
DELETE FROM dbDataEntry.Queue_Demo
OUTPUT DELETED.SnipID
WHERE
SnipID = (SELECT min(SnipID) FROM dbDataEntry.Queue_Demo WHERE UserID = 179)
答案 2 :(得分:0)
您似乎想要row_number()
函数:
delete t
from (select *, row_number () over (partition by userid order by snipid) as seq
from dbDataEntry.Queue_Demo
) t
where t.userid = 179 and
seq > 1;
答案 3 :(得分:0)
DELETE a FROM dbDataEntry.Queue_Demo a
WHERE
EXISTS (SELECT 1 FROM dbDataEntry.Queue_Demo WHERE UserId = 179 AND SnipID = a.SnipID)