我们可以使用Group by子句执行DML操作,例如Delete吗?

时间:2011-04-17 02:39:13

标签: sql-server tsql

我们可以在T-SQL中使用Group by子句执行DML操作吗?

3 个答案:

答案 0 :(得分:4)

SELECT语句 - http://msdn.microsoft.com/en-us/library/ms189499.aspx

DELETE语句 - http://msdn.microsoft.com/en-us/library/ms189835.aspx

如您所见,GROUP BY位于SELECT中,但不是DELETE,因此您无法直接使用它。它也不在INSERT语句中。

[ WITH <common_table_expression> [ ,...n ] ]  
DELETE   
    [ TOP ( expression ) [ PERCENT ] ]   
    [ FROM ]   
    { <object> | rowset_function_limited   
      [ WITH ( <table_hint_limited> [ ...n ] ) ]  
    }  
    [ <OUTPUT Clause> ]  
    [ FROM <table_source> [ ,...n ] ]   
    [ WHERE { <search_condition>   
            | { [ CURRENT OF   
                   { { [ GLOBAL ] cursor_name }   
                       | cursor_variable_name   
                   }   
                ]  
              }  
            }   
    ]   
    [ OPTION ( <Query Hint> [ ,...n ] ) ]   
[; ]  

但是使用WHERE子句或子句,可以使用GROUP BY,例如

DELETE tbl
WHERE id NOT IN (select max(id) from tbl GROUP BY date_logged)

DELETE a
FROM tbl a
JOIN (select a_id from othertbl group by a_id having count(*) >= 3) b
    ON a.id = b.a_id

答案 1 :(得分:1)

你在尝试什么

不可能.................

你可以做这样的事情

DELETE FROM #Customers
WHERE ID IN 
( SELECT    MAX(ID) FROM #Customers
GROUP BY CustName, Pincode
HAVING COUNT(*) > 1)

答案 2 :(得分:1)

您无法在GROUP BY操作的目标中直接使用DELETE,但您可以使用PARTITION BY代替GROUP BY

这是使用DELETE ... GROUP BYdeleting duplicates等任务的子查询的有用替代方法。

结合使用窗口聚合函数,您可以执行许多假设DECLARE @foo TABLE ( col1 int, col2 int ) INSERT INTO @foo SELECT 1,100 UNION ALL SELECT 1,123 UNION ALL SELECT 2,150 UNION ALL SELECT 2,200 可能允许的任务。

e.g。对于以下设置

DELETE FROM @foo
GROUP BY col1
HAVING SUM(col2) > 300

这是有效语法

;WITH cte AS
(
SELECT SUM(col2) OVER (PARTITION BY col1) AS S 
FROM @foo
) 
DELETE FROM cte
WHERE S > 300

然而,这是

{{1}}