4
   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)

How can I design the TSQL to delete rows in Table 1 based on the rows in Table 2?

In other words, iterate Table 2 one time and for each color, delete one color from Table 1 (not all the colors that equal current color of Table 2).

3
  • IMO; You need to have a PK in your tables to do that ;). Commented Oct 3, 2015 at 7:30
  • Can u add more context to your problem. Because delete from table1 where color in (select color from table2) this will delete rows which are in table 2.. Commented Oct 3, 2015 at 7:30
  • 1
    Is it possible that Table2 has more than one row with the same Color? Your sample data doesn't cover many cases, it would help if you added more rows to it. Commented Oct 3, 2015 at 8:51

2 Answers 2

4

Just number each color and delete all where number is greater then 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

Or change to:

delete from cte where rn = 1

if you want to delete only one row for each color.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for feedback...I was getting an error on "as rn)" so I moved right paren over nul)) but I'm not sure I'm getting correct behavior? See line 12 in SQL Fiddle sqlfiddle.com/#!6/9eecb7/3316
Yes you are right. There was a little bug. I have edited.
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

change to a.rownum>1 if you need to delete duplicate color

1 Comment

Hey @OP Does this work for you ? If so please do select it as an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.