删除并根据min(row_id)选择

时间:2015-01-02 15:15:14

标签: sql-server-2008 min sql-delete

我正在尝试通过从表中选择MIN(row_id)来删除记录,但查询无法正常工作 它抛出了这个错误:

  

ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOP或FOR XML。

这是我的疑问:

DELETE FROM c_dim
WHERE MIN(c_key) in (
    SELECT c_key, c_code
    FROM c_dim 
    WHERE flag = 'X' and c_code IN (
        SELECT c_code
        FROM c_dim
        WHERE flag = 'X'
        GROUP BY c_code HAVING COUNT(c_code)>1
    )
    ORDER BY c_code
)

3 个答案:

答案 0 :(得分:3)

我认为所有的子查询都可以用这个简单的

替换
;WITH CTE AS 
(
SELECT * , ROW_NUMBER() OVER (PARTITION BY c_code ORDER BY c_key) rn 
FROM c_dim
WHERE flag = 'X'
) 
DELETE FROM CTE WHERE rn > 1

答案 1 :(得分:1)

在没有所有子查询的情况下,几乎可以肯定有其他方法来优化它,但错误信息非常清楚。通过几个示例说明您收到错误的原因:

这应该有效,因为你不会在子查询中有ORDER BY。

select c_key, c_code FROM c_dim where flag = 'X' 
 and c_code IN  
 (SELECT c_code 
  FROM c_dim 
  WHERE flag = 'X' 
  GROUP BY c_code HAVING COUNT(c_code) > 1 )
 ORDER BY c_code

这不应该起作用,因为你在子查询中有ORDER BY:

Select * FROM c_dim WHERE min(c_key)
 in(select c_key, c_code FROM c_dim where flag = 'X' 
 and c_code IN  
 (SELECT c_code 
  FROM c_dim 
  WHERE flag = 'X' 
  GROUP BY c_code HAVING COUNT(c_code) > 1 )
 ORDER BY c_code)

因此,要修复写入的DELETE,只需将ORDER BY从子查询中取出,因为删除命令完全没有必要:

DELETE FROM c_dim WHERE min(c_key)
 in(select c_key, c_code FROM c_dim where flag = 'X' 
 and c_code IN  
 (SELECT c_code 
  FROM c_dim 
  WHERE flag = 'X' 
  GROUP BY c_code HAVING COUNT(c_code) > 1 )
 )

答案 2 :(得分:0)

我想c_key是独一无二的?

尝试这样的事情:

delete from c_dim where c_key = min(c_key)
and rownum = 1;/* if you want the only first */

现在,我确切地说明了这不是一个好的删除请求,但她可以帮助您解决问题。