Reputation: 21188
Our customer feeds us contracts with duplicate items. We advertise unique products. How could I select a distinct set of upcs with descriptions without doing many sub queries? Horrible example:
/*
eventID int
groupID int // This field is different between fields
upc_ean numeric(18,0)
description varchar(512) // Description is slightly different but same info
size varchar(512) // Size is slightly different but same info
*/
select A.eventid, A.upc_ean,
( select top 1 description
from myTable B
where B.eventid = A.eventid and B.upc_ean = A.upc_ean) as description,
( select top 1 size
from myTable B
where B.eventid = A.eventid and B.upc_ean = A.upc_ean) as size
from ( select distinct eventid, upc_ean from myTable) A
Is there any way to do the same thing without sub-queries, somehow joining the two together that doesn't breed records or show duplicates using eventid and upc_ean as a PK?
Upvotes: 3
Views: 7846
Reputation: 332691
You can add an ORDER BY clause if necessary to the OVER portion of the following if necessary.
WITH example AS (
SELECT a.eventid,
a.upc_ean,
a.description,
a.size,
ROW_NUMBER() OVER(PARTITION BY a.eventi, a.upc_ean) AS rank
FROM YOUR_TABLE a)
SELECT x.eventid,
x.upc_ean,
x.description,
x.size
FROM example x
WHERE x.rank = 1
SELECT x.eventid,
x.upc_ean,
x.description,
x.size
FROM (SELECT a.eventid,
a.upc_ean,
a.description,
a.size,
ROW_NUMBER() OVER(PARTITION BY a.eventi, a.upc_ean) AS rank
FROM YOUR_TABLE a) x
WHERE x.rank = 1
Upvotes: 5
Reputation: 22204
You might be able to do something like this:
SELECT A.eventid, A.upc_ean, MAX(description) as description, MAX(size) as size
FROM myTable
GROUP BY eventid, upc_ean
You should get similar results.
Upvotes: 5