I want to do something like below:
DELETE UserPredictions
GROUP BY UserId
HAVING COUNT(*) < 500
But I\'m getting a syntax error. Is
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)
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
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
Try this nested query:
DELETE FROM UserPredictions
WHERE UserId IN (SELECT UserId
FROM UserPredictions
GROUP BY UserId
HAVING COUNT(*) < 500)
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