14

这个查询

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 上

谢谢!

4

5 回答 5

25

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

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
于 2012-01-09T19:25:45.847 回答
4

SQL Server 可以进行如下更新:

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

你应该先看这里:

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

于 2012-01-09T19:26:27.297 回答
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
) 

** 如果我弄乱了列名,请原谅我,但你明白了。

于 2012-01-09T19:32:14.043 回答
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 之间存在一对一的关系。

于 2012-01-09T20:23:31.053 回答
-1

对于 SQL Server 17

UPDATE table SET col = val 
(SELECT cols FROM table .. )
于 2019-05-31T17:15:23.997 回答