除了每个组合(channel / cdn / mediaplaylist)最近的2个记录之外,删除所有记录的SQL查询是什么。
例如,我有下表:
channel cdn mediaplaylist response date
channel1 cdn1 mediaplaylist1 12 2015-02-09 10:40:00
channel2 cdn2 mediaplaylist2 19 2015-02-09 10:41:00
channel3 cdn3 mediaplaylist3 16 2015-02-09 10:42:00
channel1 cdn1 mediaplaylist1 20 2015-02-09 10:43:00
channel1 cdn1 mediaplaylist1 57 2015-02-09 10:46:00
channel2 cdn2 mediaplaylist2 83 2015-02-09 10:47:00
channel3 cdn3 mediaplaylist3 37 2015-02-09 10:48:00
channel1 cdn1 mediaplaylist1 43 2015-02-09 10:49:00
channel1 cdn1 mediaplaylist1 33 2015-02-09 10:50:00
channel2 cdn2 mediaplaylist2 79 2015-02-09 10:51:00
channel3 cdn3 mediaplaylist3 19 2015-02-09 10:52:00
channel1 cdn1 mediaplaylist1 13 2015-02-09 10:53:00
我想得到以下结果:
channel cdn mediaplaylist response date
channel1 cdn1 mediaplaylist1 12 2015-02-09 10:40:00
channel1 cdn1 mediaplaylist1 20 2015-02-09 10:43:00
channel2 cdn2 mediaplaylist2 19 2015-02-09 10:41:00
channel2 cdn2 mediaplaylist2 83 2015-02-09 10:47:00
channel3 cdn3 mediaplaylist3 16 2015-02-09 10:42:00
channel3 cdn3 mediaplaylist3 37 2015-02-09 10:48:00
答案 0 :(得分:3)
使用SQL-Server很简单,只需使用CTE和排名函数ROW_NUMBER
:
WITH CTE AS
(
SELECT RN = ROW_NUMBER() OVER (Partition By channel, cdn, mediaplaylist
Order By date DESC),
c.* -- select all columns for debugging purposes
FROM dbo.Channels c
)
DELETE FROM CTE WHERE RN > 2
我喜欢common-table-expressions,因为它们允许看到我要删除的内容。因此,您只需将DELETE
替换为SELECT *
。
答案 1 :(得分:0)
以下查询按您的方式枚举行:
select f.*,
(@rn := if(@ccp = concat_ws(':', channel, cdn, mediaplaylist), @rn + 1,
if(@ccp := concat_ws(':', channel, cdn, mediaplaylist), 1, 1)
)
) as seqnum
from following f cross join
(select @rn := 0, @ccp := '') vars
order by channel, cdn, mediaplaylist, date desc;
您希望seqnum
为1或2的值。
您可以将其放在delete
:
删除f 从以下f加入 (选择f。*, (@rn:= if(@ccp = concat_ws(':',channel,cdn,mediaplaylist),@ rn + 1, if(@ccp:= concat_ws(':',channel,cdn,mediaplaylist),1,1) ) )作为seqnum 从以下f交叉加入 (选择@rn:= 0,@ ccp:='')vars 按渠道,cdn,媒体播放列表,日期desc )ccp 在f.channel = ccp.channel和f.cdn = ccp.cdn和f.mediaplaylist = cdn.mediaplaylist 其中seqnum< 3;