根据条件更新随机行

时间:2018-05-23 09:51:31

标签: sql-server

我的桌子有多个列和行 我想根据条件随机更新50%的行。 这是我尝试过但没有工作的内容:

UPDATE dbo.tab1
SET column1 = 'A'
FROM dbo.tab1 as a
INNER JOIN (
SELECT TOP 50 percent *
FROM dbo.tab1
WHERE column2 NOT IN ('B','C','D')
ORDER BY NewID()
) as b 
on a.ID = b.ID

2 个答案:

答案 0 :(得分:0)

也许,column2包含NULL个值。尝试使用以下

CREATE TABLE tab1(
  ID int,
  column1 varchar(1),
  column2 varchar(1)
)

INSERT tab1(ID,column1)VALUES
(1,'B'),
(2,'B'),
(3,'B'),
(4,'B'),
(5,'B'),
(6,'B')


UPDATE a
SET column1 = 'A'
FROM tab1 a
INNER JOIN
  (
    SELECT TOP 50 percent *
    FROM tab1
    --WHERE column2 NOT IN ('B','C','D')
    WHERE ISNULL(column2,'') NOT IN ('B','C','D')
    ORDER BY NewID()
  ) b 
ON a.ID = b.ID


SELECT *
FROM tab1

您也可以尝试使用不带JOIN

的查询
UPDATE q
SET column1 = 'A'
FROM
  (
    SELECT TOP 50 percent *
    FROM tab1
    --WHERE column2 NOT IN ('B','C','D')
    WHERE ISNULL(column2,'') NOT IN ('B','C','D')
    ORDER BY NewID()
  ) q

答案 1 :(得分:0)

你可以利用cte来做这类事情的简短工作。这样的事情。

with MyUpdate as
(
    SELECT TOP 50 percent *
    FROM dbo.tab1
    WHERE column2 NOT IN ('B','C','D')
    ORDER BY NewID()
)

update MyUpdate
set column1 = 'A'