SQL: how to select unique rows with duplicate elements

Our client provides us with duplicate goods contracts. We advertise unique products. How can I select a separate set of upcs with descriptions without making a lot of subqueries? Awful 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 a way to do the same without subqueries, somehow combining them together so as not to create records or show duplicates using eventid and upc_ean as PK?

+3
source share
2 answers

If necessary, you can add the ORDER BY clause, if necessary, to the OVER part, if necessary.

Using CTE:

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

Without CTE:

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
+5
source

, - :

SELECT A.eventid, A.upc_ean, MAX(description) as description, MAX(size) as size
FROM myTable
GROUP BY eventid, upc_ean

.

+4

Source: https://habr.com/ru/post/1774861/


All Articles