使用子选择和多个主键字段和条件删除数据

时间:2014-01-14 11:13:58

标签: sql sql-server-2005

我有这些数据:

MyDate      id     hour   Value   insertionTime           id_agent
----------  -----  -----  ------  ----------------------  --------
2013-12-18  14     17     63      2013-12-18 11:35:47     10
2013-12-18  14     18     63      2013-12-18 11:35:47     10
2013-12-18  14     18     13      2014-01-14 11:02:27     10
2013-12-18  14     19     63      2013-12-18 11:35:47     10
2013-12-18  127    20     63      2013-12-18 11:35:47     10
...

我需要删除insertionTime2014-01-14 11:02:27不同的所有列,并为同一MyDateidhour添加另一行。

我不知道如何在单DELETE次执行中执行此操作。我不能使用聚合函数,因为PK上有多个键我不知道如何进行子选择。

理想情况下,它会是这样的:

DELETE FROM Table1 WHERE MyDate = @ADate AND id_agent = 10
AND insertionTime <> '2014-01-14 11:02:27' AND AllMyTableKeys IN
 (SELECT AllTableKeys FROM Table1 WHERE MyDate = @ADate  AND id_agent = 10
  GROUP BY AllTableKeys HAVING COUNT(*) > 1)

在示例中,我想删除第二行。

1 个答案:

答案 0 :(得分:1)

使用EXISTS制作解决方案:

SELECT * FROM MyTable a WHERE MyDate = '12/18/2013' AND id_agent = 10
AND insertionTime <> '01/14/2014 11:02:27' AND EXISTS 
  (SELECT * FROM MyTale b WHERE a.MyDate = b.MyDate AND a.hour = b.hour
   AND a.id = b.id AND insertionTime = '01/14/2014 11:02:27' AND id_agent = 10)

将其添加到DELETE表格中:

DELETE a FROM MyTable a WHERE...