Possible to do a delete with a HAVING clause?

前端 未结 5 1511
野性不改
野性不改 2020-12-06 04:02

I want to do something like below:

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

But I\'m getting a syntax error. Is

相关标签:
5条回答
  • 2020-12-06 04:37

    Not really. The having clause implies an aggregation, which means you don't have the original rows any more.

    I think you want the following:

    DELETE from UserPredictions
    where UserId in (select UserId from UserPredictions group by UserId having count(*) < 500)
    
    0 讨论(0)
  • 2020-12-06 04:42

    I don't think that is possible however you can try this

    Update : In as well as inner join can be used

    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
    

    The answer which i originally posted :

    Delete O
    FROM UserPredictions O
    INNER JOIN 
    (
     SELECT UserID 
     FROM UserPredictions  
     GROUP BY UserID
     HAVING COUNT(*) <500
     ) X
    ON O.UserID = X.UserID
    
    0 讨论(0)
  • 2020-12-06 04:44

    You can do so much with using row_number() OVER (partition by ) and CTE's, but only if your RDBMS supports it.

    Example:

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

    Additional info about the row count function:

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

    0 讨论(0)
  • 2020-12-06 04:56

    Try this nested query:

    DELETE FROM UserPredictions  
    WHERE UserId IN (SELECT UserId
                     FROM UserPredictions 
                     GROUP BY UserId
                     HAVING COUNT(*) < 500)
    
    0 讨论(0)
  • 2020-12-06 04:58

    You can use a joined subselect within the DELETE statement:

    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

    0 讨论(0)
提交回复
热议问题