首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据最新的日期戳条目删除副本

根据最新的日期戳条目删除副本
EN

Database Administration用户
提问于 2019-05-29 00:54:42
回答 1查看 51关注 0票数 0
代码语言:javascript
复制
I have a table and I'm trying to remove all the duplicate and keep the  
the rows that has the latest datestamp.

Here is the table:

email address       orgin_date   new_opt_in_date   datestamp
123@ax.tu            1900-1-1     1900-1-1          2016-3-15
123@ax.tu            1900-1-1     1900-1-1          2016-3-15
iron_man@metrix.com  2015-2-2     2016-12-26        2017-1-19
iron_man@metrix.com  2015-2-2     2016-12-26        2018-6-6
sleep@dort.st        2016-3-15    2016-3-151        2019-1-23
sleep@dort.st        2016-3-15   2016-3-151         2018-5-6

I'm trying to keep only the data that has the recent datestamp, delete the 
rest and hope that the
output will like this:
email address       orgin_date   new_opt_in_date   datestamp
 123@ax.tu            1900-1-1     1900-1-1          2016-3-15
 iron_man@metrix.com  2015-2-2     2016-12-26        2018-6-6
 sleep@dort.st        2016-3-15    2016-3-151        2019-1-23

DELETE FROM `tablename` 
WHERE datestamp
NOT IN (
SELECT * FROM (
  SELECT MAX(datestamp) FROM tablename 
    GROUP BY emailaddress
 ) 
 )    
but nothing it didn't work     
EN

回答 1

Database Administration用户

回答已采纳

发布于 2019-05-29 01:17:03

您可以使用CTE为每个电子邮件地址添加一个从最新日期标记1开始的行号,然后删除所有其余的。

代码语言:javascript
复制
;WITH x AS 
(
  SELECT email, origin_date, new_opt_in_date, datestamp,
    rn = ROW_NUMBER() OVER (PARTITION BY email ORDER BY datestamp DESC)
  FROM dbo.tablename
)
DELETE x WHERE rn > 1;
票数 4
EN
页面原文内容由Database Administration提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://dba.stackexchange.com/questions/239266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档