Select a unique combination of two columns

7.5k views Asked by At

Sample data:

ProductID    PackingID
-------      ---------
1            2
1            2
3            2
3            2
1            1
2            1
3            2

I have the above sample data. What i want is to select the unique (not distinct) rows of the combination productID and packingID. In the above example the only matching results are

ProductID    PackingID
-------      ---------
1            1
2            1

These rows are the only unique combinations of ProductID and PackingID together. I do not want Distinct results because it will give me one of all the other combinations.

3

There are 3 answers

0
Dharmesh Porwal On BEST ANSWER
SELECT PRODUCTID,PACKINGID FROM DTEMP
GROUP BY PRODUCTID,PACKINGID
HAVING COUNT(PRODUCTID)=1 
ORDER BY 1;

You can try this one this is how i do in oracle ... to get the unique rows without using distinct.

0
Tejesh On

your table should be like:

 uniqueID   ProductID   PackingID
   1          x            y
   2          x            y
   3          z            x

Query:

SELECT uniqueID,ProductID,PackingID
FROM yourtable
WHERE uniqueID IN
(
    SELECT MIN(uniqueID)
    FROM yourtable
    GROUP BY ProductID,PackingID
)
1
Dan On
SELECT ProductID, PackingID
FROM yourtable
GROUP BY ProductID, PackingID
HAVING COUNT(*) = 1