SQL Server 2008:基于其他表更新列

时间:2012-03-05 21:06:30

标签: sql-server-2008 count

TableA id int, match char(15), multiple char(10)

int match multiple
1   100  
2   101
3   102
4   103

TableB match char(15), match2 char(10)

match  match2
100    ABC
100    NBG
101    NYF
102    NHW
102    UYQ
103    WOT

现在,我想填充TableA.multiple = "YES"如果在TableB中进行相应的匹配,则存在多个匹配2。

预期结果。

int match multiple
1   100    YES
2   101    NULL
3   102    YES
4   103    NULL

提前致谢!

我的失败尝试:

Update A 
SET multiple = 'YES' 
From tableA A
Inner join tableB B ON A.match = B.match
WHERE (Select count(distinct(B.match2)) from TableB) > 2

3 个答案:

答案 0 :(得分:4)

从一个额外详细的版本开始,只是为了清晰起见:

UPDATE TableA
SET multiple = 'YES'
WHERE match in (
    -- isolate the multiples
    SELECT match from (
        -- count the matches
        SELECT count(*) as c, match from TableB
        GROUP BY match ) x
    WHERE c > 1
)

使用HAVING子句,您可以更改此...

    SELECT match from (
        SELECT count(*) as c, match from TableB
        GROUP BY match ) x
    WHERE c > 1

......对此:

   SELECT match from TableB
   GROUP BY match
   HAVING count(*) > 1

现在我们有:

UPDATE TableA
SET multiple = 'YES'
WHERE match in (
   SELECT match from TableB
   GROUP BY match
   HAVING count(*) > 1
)

我确信它可以变得更加紧凑,但我个人对包含非显而易见的UPDATE条款的JOIN语句感到困惑,特别是在半夜接到电话时“数据库无法运行!”

Don't Make Me Think也适用于编码。

答案 1 :(得分:0)

UPDATE tableA
SET multiple = 'YES'
FROM TableA AS a
JOIN (SELECT match FROM tableB GROUP BY match HAVING COUNT(*) > 1) AS b ON a.match = b.match

答案 2 :(得分:-3)

UPDATE TableA a
SET multiple='YES'
FROM Tablea a,(SELECT match FROM Tableb GROUP BY match HAVING COUNT(*)>1)b
WHERE a.match=b.match