Table 1
Color
------
Red
Red
Blue
Table 2
Color
------
Red
Blue
Result
Red (since red in Table 1 2x and only 1x in Table 2)
如何根据表2中的行设计TSQL来删除表1中的行?
换句话说,迭代表2一次,对于每种颜色,从表1中删除一种颜色(不是所有与表2当前颜色相同的颜色)。
答案 0 :(得分:4)
只需为每种颜色编号并删除所有数字大于1的所有颜色:
;with cte as(select t1.*, row_number() over(partition by t1.color
order by(select null)) as rn
from table1 t1
join table2 t2 on t1.color = t2.color)
delete from cte where rn > 1
或改为:
delete from cte where rn = 1
如果您只想为每种颜色删除一行。
答案 1 :(得分:2)
DECLARE @Table1 Table (color nvarchar(4))
INSERT INTO @Table1 Values ('Red')
INSERT INTO @Table1 Values ('Red')
INSERT INTO @Table1 Values ('Blue')
DECLARE @Table2 Table (color nvarchar(4))
INSERT INTO @Table2 Values ('Red')
INSERT INTO @Table2 Values ('Blue')
DELETE a
FROM (
SELECT t1.*,
row_number() OVER (
PARTITION BY t1.color ORDER BY (SELECT 1)
) AS rownum
FROM @Table1 t1
WHERE t1.color IN (
SELECT t2.color
FROM @Table2 t2
)
) a
WHERE a.rownum =1
如果您需要删除重复的颜色,请更改为a.rownum> 1