使用join更新表列

时间:2013-03-02 13:30:31

标签: sql sql-server-2008 sql-update

任何人都可以帮助这个sql代码,我正在尝试将第一场比赛的表列FirstURLForSite更新为1,但我正在努力使用代码,我只是想更新第一场比赛。

任何人都可以提供帮助,希望你能理解我想要做的事情。

update [dbo].[at_WebsitesSearch]
set [FirstURLForSite] = 1
where(

left outer join
select min(ID) as rowid, [BaseURL]
from [dbo].[at_WebsitesSearch]
group by [BaseURL]) as FirstMatch on
[dbo].[at_WebsitesSearch].id = FirstMatch.rowid
where FirstMatch.rowid is null

数据示例

BasesURL                                FirstURLForSite
http://asia1x1.net/                         1
http://asia1x1.net/                         0
http://asia1x1.net/                         0

http://australia.bedandbreakfasts.net/      1
http://australia.bedandbreakfasts.net/      0
http://australia.bedandbreakfasts.net/      0

2 个答案:

答案 0 :(得分:3)

<击>

<击>

尝试一下,我正在尝试修复您当前的查询

UPDATE  a
SET     a.FirstURLForSite = 1
FROM    at_WebsitesSearch a
        LEFT JOIN 
        (
            SELECT  MIN(ID) AS rowid, BaseURL
            FROM    at_WebsitesSearch
            GROUP   BY BaseURL
        ) FirstMatch
            ON FirstMatch.rowid = a.id
WHERE   FirstMatch.rowid IS NULL

<击>

更新1

WITH records
AS
(
    SELECT  BasesURL, FirstURLForSite,
            ROW_NUMBER() OVER (PARTITION BY BasesURL ORDER BY BasesURL ASC) rn
    FROM    at_WebsitesSearch
)
UPDATE  records
SET     FirstURLForSite = CASE WHEN rn = 1 THEN rn ELSE 0 END

答案 1 :(得分:0)

  

你必须做这样的事情。还要检查下面的小提琴演示。

;WITH CTE  
AS  
(  
    SELECT  BasesURL, FirstURLForSite,  
        ROW_NUMBER() OVER (PARTITION BY BasesURL   
                            ORDER BY BasesURL DESC) RN  
    FROM    at_WebsitesSearch  
)  
UPDATE  CTE  
SET     FirstURLForSite = 1  
WHERE RN = 1  

SQL Fiddle Demo