I have a table UNIQUES like :
ID DESC DATE NUMBER Amount
100 TEST1 01-01-18 1009674 10.20
100 TEST2 01-02-18 1009674 245.10
100 TEST3 01-03-18 1009942 156.000
100 TEST4 02-14-18 00042EX 154.6
100 TEST5 04-15-18 00042EX 25.10
100 TEST6 05-20-18 1011055 1564.0
And I would like to get the unique records where the Number field has not duplicate or is not repeating.
Result expected:
ID DESC DATE NUMBER AMOUNT
100 TEST3 01-03-18 1009942 156.000
100 TEST6 05-20-18 1011055 1564.0
Query I'm using:
SELECT * FROM UNIQUES
WHERE NUMBER NOT IN (SELECT NUMBER FROM
UNIQUES GROUP BY NUMBER HAVING COUNT(NUMBER)=1)
Any assistance or help would be really appreciated.
I think you are pretty close
SELECT * FROM UNIQUES
WHERE NUMBER IN (SELECT NUMBER FROM
UNIQUES GROUP BY NUMBER HAVING COUNT(NUMBER)=1)
And you want:
ID DESC DATE NUMBER AMOUNT
100 TEST3 01-03-18 1009942 156.000
100 TEST6 05-20-18 1011055 1564.0
And my answer gives:
There are several good ways to do this, I'm just going with the simplest based upon the question by just changing it from NOT IN
to IN
You can use subquery
:
select u.*
from uniques u
where not exists (select 1 from uniques u1 where u1.number = u.number and u1.desc <> u.desc);
I would just use window functions:
select u.*
from (select u.*, count(*) over (partition by number) as cnt
from uniques u
) u
where cnt = 1;
SELECT SRC.ID, SRC.DESC, SRC.DATE, SRC.NUMBER, SRC.Amount
FROM UNIQUES AS SRC
INNER JOIN (SELECT NUMBER FROM UNIQUES GROUP BY NUMBER HAVING COUNT(*)=1) AS NonDupe
ON SRC.Number = NonDupe.Number
I would avoid using column names such as DESC, DATE and NUMBER as they occur in the list of SQL and ODBC reserved words.
Aside from the not exists
method, you can outer join
the table to itself, and check for nulls in the "duplicate" table.
select *
from
uniques u
left outer join uniques dup
on (u.NUMBER=dup.NUMBER)
where
dup.NUMBER is null
This works because the left outer join will return everything from the "left" table (aliased to u
above), and it will return null
values from the "right" table (aliased to dup
above) if there is no row found with the join on
criteria.
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.