如何使用SQL中的临时表删除最旧的记录并保留最近的记录?

时间:2017-09-17 09:50:16

标签: sql sql-server tsql

如何删除最旧的记录,但在下面给出的示例中保留SQL中的最近记录?

在临时表中预期输出显示和记录删除而不影响主表

电流:

StockId   Name   CreatedDate   Status 
1        Apple     10/09/2017     2
1        Apple     11/09/2017     2
1        Apple     12/09/2017     2
2        Orange    15/09/2017     2
2        Orange    16/09/2017     1

预期:

StockId   Name   CreatedDate   Status 
1        Apple     12/09/2017     2
2        Orange    16/09/2017     1

3 个答案:

答案 0 :(得分:2)

尝试这样的事情:

WITH cte
AS
(
SELECT *,row_number() over (partition by StockId, Name order by CreatedDate desc) as row_number 
FROM yourtable
) DELETE FROM cte WHERE row_number>1

答案 1 :(得分:1)

如果您只想将每个库存ID的最新记录放入新表中,请使用插入选择。使用ROWNUMBER对记录进行排名。

insert into temp (stockid, name, createddate, status)
select stockid, name, createddate, status
from
(
  select 
    stockid, name, createddate, status,
    rownumber() over (partition by stockid order by createddate desc) as rn
  from mytable
)
where rn = 1;

答案 2 :(得分:0)

您可以使用显示StockId和最新数据的嵌套查询。然后,删除原始表中嵌套查询中不包含的所有行:

/* Create few records in this table */
INSERT INTO MyTable VALUES(1, 1, 'Apple', '2017/09/10', 2);
INSERT INTO MyTable VALUES(2, 1, 'Apple', '2017/09/11', 2);
INSERT INTO MyTable VALUES(3, 1, 'Apple', '2017/09/12', 2);
INSERT INTO MyTable VALUES(4, 2, 'Orange', '2017/09/15', 2);
INSERT INTO MyTable VALUES(5, 2, 'Orange', '2017/09/16', 2);

DELETE FROM MyTable
WHERE (StockId, CreatedData) NOT IN 
                            (
                              SELECT StockId, Max(CreatedData) 
                              FROM MyTable GROUP BY StockId
                             );

/* result*/
StockId   Name   CreatedDate   Status 
 1        Apple   2017/09/12     2
 2        Orange  2017/09/16     1