TSQL Comparing two Sets

后端 未结 6 2031
野的像风
野的像风 2021-01-18 03:58

When two sets are given

s1 ={ a,b,c,d} s2={b,c,d,a}

(i.e)

TableA

Item
a
b
c
d

TableB

Item
b
c
d
a

How to write Sql quer

6条回答
  •  广开言路
    2021-01-18 05:02

    Since this thread was very helpful to me, I thought I'd share my solution.

    I had a similar problem, perhaps more generally applicable than this specific single-set comparison. I was trying to find the id of an element that had a set of multi-element child elements that matched a query set of multi-element items.

    The relevant schema information is:

    table events, pk id
    table solutions, pk id, fk event_id -> events
    table solution_sources, fk solutionid -> solutions
       columns unitsourceid, alpha
    

    Query: find the solution for event with id 110 that has the set of solution_sources that match the set of (unitsourceid, alpha) in ss_tmp. (This can also be done without the tmp table, I believe.)

    Solution:

    with solutionids as (
      select y.solutionid from (
         select ss.solutionid, count(ss.solutionid) x 
            from solutions s, solution_sources ss 
            where s.event_id = 110 and ss.solutionid = s.id 
            group by ss.solutionid
      ) y where y.x = ( select count(*) from ss_tmp )
    ) 
    select solutionids.solutionid  from solutionids where
    (
    select case
       when count(*) = ( select count(*) from ss_tmp ) then true
       else false
       end
        from 
           ( SELECT unitsourceid, alpha FROM solution_sources 
                where solutionid = solutionids.solutionid
              INTERSECT
             SELECT unitsourceid, alpha FROM ss_tmp ) x
    )
    

    Tested against a test query of 4 items and a test db that had a matching solution (same number of child elements, each that matched), several completely non-matching solutions, and 1 solution that had 3 matching child elements, 1 solution that had all 4 matching child elements, plus an additional child, and 1 solution that had 4 child elements of which 3 of the 4 matched the query. Only the id of the true match was returned.

    thanks a lot -Linus

提交回复
热议问题