Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a HAVING clause in an UPDATE statement

This query

SELECT
FirstName, LastName, NCAAStats.AccountId, College_Translator.school_name, StatTypeId, COUNT(*) AS 'Count'
FROM NCAAstats
INNER JOIN College_Translator
ON College_Translator.AccountID = NCAAstats.AccountId
GROUP BY FirstName, LastName, NCAAStats.AccountId, College_Translator.school_name, CalendarYear, StatTypeId
HAVING COUNT(*) >1
ORDER BY 'Count' DESC

Selects records that I would like to set an ISValid bit to 0.

These records are records that appear twice in my database due to an input error.

I'm looking for something like:

UPDATE NCAAstats
SET IsValid = 0
WHERE (my select statement)

This is on MS SQL SERVER 2008

Thanks!

like image 474
Tyler DeWitt Avatar asked Jan 09 '12 19:01

Tyler DeWitt


People also ask

Can WHERE clause be used in UPDATE DELETE statement?

DELETE Syntax Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be deleted!

When can we use HAVING clause?

To complement a GROUP BY clause, use a HAVING clause to apply one or more qualifying conditions to groups after they are formed. The effect of the HAVING clause on groups is similar to the way the WHERE clause qualifies individual rows.

What is the example of HAVING clause?

In this condition, we will use HAVING Clause. SELECT Department, sum(Salary) as Salary FROM employee GROUP BY department HAVING SUM(Salary) >= 50000; Example 2: Suppose, a teacher wants to announce the toppers in class.


1 Answers

You can join to that subquery like so:

update n1 set
    isvalid = 0
from
    ncaastats n1
    inner join (
        SELECT
        FirstName, LastName, NCAAStats.AccountId, College_Translator.school_name, StatTypeId, COUNT(*) AS 'Count'
        FROM NCAAstats
        INNER JOIN College_Translator
        ON College_Translator.AccountID = NCAAstats.AccountId
        GROUP BY FirstName, LastName, NCAAStats.AccountId, College_Translator.school_name, CalendarYear, StatTypeId
        HAVING COUNT(*) >1
    ) n2 on
        n1.accountid = n2.accountid
like image 137
Eric Avatar answered Sep 16 '22 14:09

Eric