Return only the collumn that exists in all rows

  • I am a newbie to SQL server and hoping someone can write a single query to replace my manual way of doing the following:

    DECLARE @tbl1 table( id int)

    INSERT into @tbl1(id)

    values(1)

    INSERT into @tbl1(id)

    values(2)

    INSERT into @tbl1(id)

    values(3)

    DECLARE @tbl2 table( id int, val varchar(1))

    INSERT into @tbl2(id,val)

    values(1,'A')

    INSERT into @tbl2(id,val)

    values(1,'B')

    INSERT into @tbl2(id,val)

    values(2,'A')

    INSERT into @tbl2(id,val)

    values(3,'A')

    INSERT into @tbl2(id,val)

    values(3,'B')

    INSERT into @tbl2(id,val)

    values(3,'C')

    SELECT val from @tbl2

    WHERE id = 1

    INTERSECT

    SELECT val from @tbl2

    WHERE id = 2

    INTERSECT

    SELECT val from @tbl2

    WHERE id = 3

    'A' is return because only A exists in all rows of @tbl1. I would like to avoid using a cursor and dynamic SQL.

    Thanks

    Faizel

  • select b.val

    from @tbl1 as a

    inner join @tbl2 as b

    on a.id = b.id

    group by val

    having COUNT(val) = (select COUNT(id) from @tbl1)

    ---------------------------------------------------------

    It takes a minimal capacity for rational thought to see that the corporate 'free press' is a structurally irrational and biased, and extremely violent, system of elite propaganda.
    David Edwards - Media lens[/url]

    Society has varying and conflicting interests; what is called objectivity is the disguise of one of these interests - that of neutrality. But neutrality is a fiction in an unneutral world. There are victims, there are executioners, and there are bystanders... and the 'objectivity' of the bystander calls for inaction while other heads fall.
    Howard Zinn

  • Perfect! Thank you very much.:-)

  • Glad to help and welcome to SQL Server Central 😉

    ---------------------------------------------------------

    It takes a minimal capacity for rational thought to see that the corporate 'free press' is a structurally irrational and biased, and extremely violent, system of elite propaganda.
    David Edwards - Media lens[/url]

    Society has varying and conflicting interests; what is called objectivity is the disguise of one of these interests - that of neutrality. But neutrality is a fiction in an unneutral world. There are victims, there are executioners, and there are bystanders... and the 'objectivity' of the bystander calls for inaction while other heads fall.
    Howard Zinn

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply