1

I have a single table as below and I want the Products which are having same Lot Numbers in different countries. I need all the records.

Table:

╔════════════╦════════════╦═════════╗
║ Product ID ║ Lot Number ║ Country ║
╠════════════╬════════════╬═════════╣
║          1 ║ L01        ║ US      ║
║          2 ║ L02        ║ US      ║
║          3 ║ L01        ║ UK      ║
║          4 ║ L02        ║ US      ║
║          5 ║ L03        ║ UK      ║
║          6 ║ L03        ║ US      ║
║          7 ║ L03        ║ US      ║
╚════════════╩════════════╩═════════╝

Required Output:

╔════════════╦════════════╦═════════╗
║ Product ID ║ Lot Number ║ Country ║
╠════════════╬════════════╬═════════╣
║          1 ║ L01        ║ US      ║
║          3 ║ L01        ║ UK      ║
║          5 ║ L03        ║ UK      ║
║          6 ║ L03        ║ US      ║
║          7 ║ L03        ║ US      ║
╚════════════╩════════════╩═════════╝
0

1 Answer 1

2

That one is relatively straightforward:

SELECT *
FROM MyTable t1
WHERE EXISTS (
    SELECT * FROM MyTable t2
    WHERE t1.LotNumber=t2.LotNumber AND t1.Country <> t2.Country
)

This is self-explanatory: you want all rows such that there's at least one other row with the same lot number, but a different country. Note that in order to express this in SQL using the same table twice in the same query you need to give your table an alias: in the query above, that's t1 and t2.

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

2 Comments

hi @dasblinkenlight I am wondering why the below query is not working. Any idea? SELECT productid, lotnumber, country FROM MyProducts t1 WHERE t1.ProductID in( SELECT ProductID FROM MyProducts t2 WHERE t1.LotNumber=t2.LotNumber AND t1.Country <> t2.Country )
@Rams The logic connecting the table t1 from the outer query to the table t2 from the subquery is strange: I do not see what rows it should be returning, given that the constraints go both ways (subquery constraints the outer query by ID, and the outer query constraints the subquery by LotNumber and Country).

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.