SQL-server delete复制复杂查询

时间:2016-04-07 09:51:37

标签: sql sql-server sql-delete

我在这个查询中工作了好几天。所以我有一个数据库,服务器应该每天更新一次。如果它每天更新两次或三次,那么我有重复。我可以通过DATETIME值Date_Inserted找到重复项。更新日期还有另一个DATETIME值。我能理解当我有重复时,就是当我有超过300条记录时,我可以通过这个查询找到它:

  SELECT Date_Inserted, Date_Last_Updated, COUNT(Date_Inserted) 
    FROM   dbo.[Yacht&Sail_Analytical]
    GROUP BY Date_Inserted, Date_Last_Updated
     HAVING COUNT(Date_Inserted) > 300

此外,当我想查看重复项何时发生时,我可以通过此查询找到它:

 SELECT TOP (100) PERCENT Date_Last_Updated, Date_Inserted, COUNT(*) AS Expr1
    FROM     dbo.[Yacht&Sail_Analytical]
    GROUP BY Date_Last_Updated, Date_Inserted
    HAVING (Date_Last_Updated = '2015 - 12 - 10 00:00:00.000')
    ORDER BY Expr1 DESC.

因为我只想删除在特定时间在特定时间创建的记录,我可以从SELECT查询中找到的记录,我正在使用此

DELETE  
FROM dbo.[Yacht&Sail_Analytical]
WHERE Date_Last_Updated NOT IN 
(SELECT Date_Inserted, Date_Last_Updated, COUNT(Date_Inserted) 
             FROM dbo.[Yacht&Sail_Analytical] LEFT JOIN
             (SELECT Date_Last_Updated, Date_Inserted, COUNT(*) AS Expr1
                FROM     dbo.[Yacht&Sail_Analytical]
                GROUP BY Date_Last_Updated, Date_Inserted
                HAVING (Date_Last_Updated = '2015 - 12 - 10 00:00:00.000')) AS ID
                )
)

哪个不行。我究竟做错了什么?

错误讯息:

  

Msg 102,Level 15,State 1,Line 9语法不正确')'。

1 个答案:

答案 0 :(得分:1)

我更多地研究了这个。我的查询未正确构建。对我有用的是:

DELETE
FROM dbo.[Yacht&Sail_Analytical]

WHERE
(
MONTH(Date_Inserted)=12 AND   
YEAR(Date_Inserted)=2015 AND
DAY(Date_Inserted)=11) 

 AND 
[a/a] IN 
( SELECT [a/a] 
FROM dbo.[Yacht&Sail_Analytical]
WHERE Date_Inserted > CONVERT (DATETIME,'2015-12-11 16:00:00.457'))

哪个更简单。 *

  

a / a是每一行的唯一ID。

    *