在UPDATE语句中使用HAVING子句

时间:2012-01-09 19:20:34

标签: sql sql-server-2008 having

此查询

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

选择我想将ISValid位设置为0的记录。

这些记录是由于输入错误而在我的数据库中出现两次的记录。

我正在寻找类似的东西:

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

这是在MS SQL SERVER 2008上

谢谢!

5 个答案:

答案 0 :(得分:16)

您可以像这样加入该子查询:

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

答案 1 :(得分:2)

SQL Server可以执行以下更新:

UPDATE table SET col=vaue
FROM (
  SELECT ......
)

你应该先看看这里:

http://msdn.microsoft.com/en-us/library/aa260662(v=sql.80).aspx

答案 2 :(得分:2)

以上是很好的建议....这是另一种简单的方法:

update ncaastats set isvalid = 0
where accountId in (
    SELECT AccountId
    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
) 

**如果我把列名搞砸了,请原谅我,但你明白了。

答案 3 :(得分:1)

使用CTE,并执行基本上是自我加入的

;with NCAAstatsToUpdate(
    SELECT AccountId 
    FROM NCAAstats n
        INNER JOIN College_Translator ct
      ON ct.AccountID = n.AccountId 
    GROUP BY FirstName, LastName, n.AccountId, ct.school_name, 
         CalendarYear, StatTypeId 
    HAVING COUNT(*) >1 )
UPDATE NCAAstats 
SET IsValid=0
FROM NCAAstats n
inner join NCAAstatsToUpdate u
    on n.AccountId = u.AccountId

或者更好的是,使用窗口函数。

;with NCStats as(
 Select distinct row_number() over (partition by FirstName, LastName, n.AccountId, ct.school_name, 
         CalendarYear, StatTypeId order by n.accountId) rw, n.*
 FROM NCAAstats n
        INNER JOIN College_Translator ct
      ON ct.AccountID = n.AccountId 
)
Update NCStats
Set IsValid=0
Where rw>1

请注意,第二个记录不会将“第一个”记录更新为无效,并且它假定NCAAstats和College_Translator之间存在1对1的关系。

答案 4 :(得分:-1)

对于SQL Server 17

UPDATE table SET col = val 
(SELECT cols FROM table .. )