Search
 
SCRIPT & CODE EXAMPLE
 

SQL

sql 2 way of select unique

/** Find the higher id values of duplicates, distinct only added for clarity */
    SELECT  distinct d2.id
    FROM    dupes d1
        INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
    WHERE d2.id > d1.id

/*
id|
--|
 5|
 6|
 8|
 9|
10|
*/

/** Use the previous query in a subquery to exclude the dupliates with higher id values */
SELECT  *
FROM    dupes
WHERE   id NOT IN (
    SELECT  d2.id
    FROM    dupes d1
        INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
    WHERE d2.id > d1.id
)
ORDER BY word, num;

/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/
Comment

sql 2 way of select unique

WITH CTE AS (
    SELECT  *
           ,row_number() OVER(PARTITION BY word, num ORDER BY id) AS row_num
    FROM    dupes
)
SELECT  word, num, id 
FROM    cte
WHERE   row_num = 1
ORDER BY word, num;

/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/
Comment

PREVIOUS NEXT
Code Example
Sql :: create postgres table 
Sql :: sql server select rows by distinct column 
Sql :: lost connection to mysql server during query when dumping table 
Sql :: mysql date_format 
Sql :: how to start with sql 
Sql :: difference between in and between in sql 
Sql :: pgadmin postgres ERROR: database is being accessed by other users 
Sql :: postgres stored procedure 
Sql :: missing left parenthesis error in sql 
Sql :: Select All From A Table In A MySQL Database 
Sql :: How do I UPDATE from a SELECT in SQL Server? 
Sql :: mysql sublime build system 
Sql :: devilbox mysqldump 
Sql :: time in sql server 
Sql :: select where mysql 
Sql :: postgresql isnull with max 
Sql :: exclude last comma separated string mysql 
Sql :: oracle for loop on list 
Sql :: getting customers with no orders sql 
Sql :: mysql average from two table 
Sql :: sql revert migration 
Sql :: delete from table where length sql 
Sql :: compound trigger oracle 
Sql :: sql max count 
Sql :: mysql loop through databases and execute query 
Sql :: insert into table sql 
Sql :: parent child hierarchy in sql 
Sql :: mysql show create db 
Sql :: sql timezone 
Sql :: mysql comparing dates 
ADD CONTENT
Topic
Content
Source link
Name
7+7 =