简体   繁体   中英

Values from one column common to values in another column

I have a table where I'm concerned with two columns, namely orderNumber and productCode. The table is configured as such

orderNumber    productCode
1000                a
1000                b
1000                c
1001                a
1001                f     
1001                d     ...

I need to find the productCode common to all orders. How do I go about this task?

One way ( SQL Fiddle )

SELECT productCode
FROM   OrderProducts
GROUP  BY productCode
HAVING COUNT(DISTINCT orderNumber) = (SELECT COUNT(DISTINCT orderNumber)
                                      FROM   OrderProducts) 

If orderNumber,productCode is guaranteed unique and you have a separate table with all orders then

SELECT productCode
FROM   OrderProducts
GROUP  BY productCode
HAVING COUNT(orderNumber) = (SELECT COUNT(*) FROM Orders) 

would be better.

See Divided We Stand: The SQL of Relational Division for some alternate methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM