可以用HAVING子句删除吗?

时间:2012-07-29 01:44:51

标签: sql sql-server sql-server-2008

我想做类似下面的事情:

DELETE UserPredictions
  GROUP BY UserId
  HAVING COUNT(*) < 500

但我收到语法错误。甚至可以在SQL Server中使用HAVING子句进行删除,还是必须将计数滚动到CTE中并使用连接执行删除?

5 个答案:

答案 0 :(得分:46)

不是真的。 having子句意味着聚合,这意味着您不再拥有原始行。

我想你想要以下内容:

DELETE from UserPredictions
where UserId in (select UserId from UserPredictions group by UserId having count(*) < 500)

答案 1 :(得分:18)

您可以在DELETE声明中使用已加入的子选择:

DELETE a
FROM   UserPredictions a
JOIN
(
    SELECT   UserId
    FROM     UserPredictions
    GROUP BY UserId
    HAVING   COUNT(1) < 500
) b ON a.UserId = b.UserId

SQLFiddle Demo

答案 2 :(得分:10)

尝试这个嵌套查询:

DELETE FROM UserPredictions  
WHERE UserId IN (SELECT UserId
                 FROM UserPredictions 
                 GROUP BY UserId
                 HAVING COUNT(*) < 500)

答案 3 :(得分:1)

使用row_number() OVER (partition by )和CTE可以做很多事情,但前提是您的RDBMS支持。

示例:

WITH CTE AS 
(
    SELECT UserId,
    ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY UserId) AS rowcount    
    FROM UserPredictions
)
DELETE FROM CTE
WHERE rowcount < 500

有关行计数功能的其他信息:

https://docs.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql?view=sql-server-2017

答案 4 :(得分:0)

我不认为这是可能的,但你可以试试这个

更新:In以及inner join可以使用

Declare @Sample table 
(
UserID int,
col2 int
)
INSERT INTO @Sample
SELECT 1,50 UNION ALL
SELECT 1,100 UNION ALL
SELECT 2,150 UNION ALL
SELECT 2,200 union all
Select 4,500

DeLETE FROM @Sample  
WHERE UserID IN (SELECT UserID
             FROM @Sample 
             GROUP BY UserID
             HAVING COUNT(*) > 1)


 Delete O
 FROM @Sample O
 INNER JOIN 
 (
  SELECT UserID 
  FROM @Sample  
  GROUP BY UserID
 HAVING COUNT(*) >1
 ) X
ON O.UserID = X.UserID

我最初发布的答案:

Delete O
FROM UserPredictions O
INNER JOIN 
(
 SELECT UserID 
 FROM UserPredictions  
 GROUP BY UserID
 HAVING COUNT(*) <500
 ) X
ON O.UserID = X.UserID