1

Let's say I have the following data:

Number  TagValue
1       MLB
1       NFL
2       MLB
2       NFL
3       MLS
3       NFL
4       NFL

I want to return the following:

Number  TagValue
1       MLB
1       NFL
2       MLB
2       NFL

The request is to look each number- tag value combo and see if it has BOTH MLB and NFL. If it does not I do not want to return it. A simple where clause will return:

Number  TagValue
1       MLB
1       NFL
2       MLB
2       NFL
3       NFL
4       NFL

I do not want this.

1
  • @GordonLinoff: Record 3 in the original is MLS not MLB. He just wants to exclude 3 and 4. Commented Aug 24, 2018 at 15:10

3 Answers 3

1

If you only want to show the records where the number has both tags and the actual tag of the record is one of the tags, then a straight forward solution would be a disjunction of two times an equal operation and an EXISTS.

SELECT t1.number,
       t1.tagvalue
       FROM elbat t1
            WHERE t1.tagvalue = 'MLB'
                  AND EXISTS (SELECT *
                                     FROM elbat t2
                                     WHERE t2.number = t1.number
                                           AND t2.tagvalue = 'NFL')
                   OR t1.tagvalue = 'NFL'
                      AND EXISTS (SELECT *
                                         FROM elbat t2
                                         WHERE t2.number = t1.number
                                               AND t2.tagvalue = 'MLB');
Sign up to request clarification or add additional context in comments.

Comments

1

You can use exists :

select t.*
from table t
where exists (select 1 from table t1 where t1.number = t.number and t1.tagvalue = 'MLB') and
      exists (select 1 from table t1 where t1.number = t.number and t1.tagvalue = 'NFL')

2 Comments

i just tried this and still returns results that have just one of MLB and NFL?
@skimchi1993. . . You need two exists.
0

If you want to return all numbers that have both codes, you can do:

select number
from t
where tagvalue in ('MLB', 'NFL')
group by number
having min(tagvalue) <> max(tagvalue);

I see little utility in returning multiple rows in this case.

If you want numbers with only one team, then:

select number, max(tagvalue)
from t
where tagvalue in ('MLB', 'NFL')
group by number
having min(tagvalue) = max(tagvalue);

Comments

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.