0

I have a table where each address has different types, for each type a row. How to find the addresses where for the exact types i need?

Eg.

ID  TypID   Street
1   1       Street 1
1   2       Street 1
2   2       Street 2
3   1       Street 3
3   2       Street 3

In the above i need to find addresses which has type 1 and 2. That query result should be adresses with id 1 and 3.

0

3 Answers 3

1

Group by the id and then count the different typeids in the having clause

select id from your_table
where typeid in (1,2)
group by id
having count(distinct typeid) = 2
Sign up to request clarification or add additional context in comments.

Comments

1

You can use INTERSECT for this

select id
from tbl
where typid = 1
intersect
select id
from tbl
where typid = 2

although it won't work in mysql if that happens to be the database you're using.

1 Comment

@sysboard It does work, as you can see here sqlfiddle.com/#!6/6abff/1/0 . Perhaps you are not actually using sql server and are using a different database?
1

This can be done with a inner join like the below

select y2.*
from <your_table> Y1
JOIN <your_table> Y2
ON   Y1.ID = Y2.ID
AND  Y1.Type_id in (1,2)
AND  Y2.ID in (1,3)

1 Comment

Thanks for the Response. Juergen d has posted before you and his code works for me so i vote yours up.

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.