41

我想做如下的事情:

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

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

4

5 回答 5

54

并不真地。have 子句意味着聚合,这意味着您不再拥有原始行。

我认为您想要以下内容:

DELETE from UserPredictions
where UserId in (select UserId from UserPredictions group by UserId having count(*) < 500)
于 2012-07-29T01:52:29.273 回答
27

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 演示

于 2012-07-29T02:57:33.247 回答
11

试试这个嵌套查询:

DELETE FROM UserPredictions  
WHERE UserId IN (SELECT UserId
                 FROM UserPredictions 
                 GROUP BY UserId
                 HAVING COUNT(*) < 500)
于 2012-07-29T01:53:16.660 回答
3

您可以使用和 CTE 做很多事情row_number() OVER (partition by ),但前提是您的 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

于 2018-10-23T19:34:16.117 回答
0

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

更新:Ininner 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
于 2012-07-29T01:55:04.140 回答