简体   繁体   中英

sql SELECT query not doing the opposite

im using a query that checks for duplicate values, but now i want it to do the opposite of this query:

SELECT * FROM orders WHERE buy_date (SELECT buy_date FROM orders GROUP BY buy_date HAVING count(*)>1)

Result: 结果

I tried changing HAVING count(*)=0 / HAVING count(*)<1 put it returns nothing

The limiting clause having count(*) < 1 will not return values. You cannot return a recordset with half a row! Try HAVING count(*) < 2 which will return rows with a count of 1.

You may also want to check out the DISTINCT function which returns distinct values.

I suppose you consider duplicate two orders with the same buy_date and different id (I suppose id is the name of PK field)

For duplicate - try this:

SELECT o1.*
FROM orders o1
WHERE EXISTS(
    SELECT 'duplicate'
    FROM orders o2
    WHERE o1.id <> o2.id
   AND o1.buy_date = o2.buy_date
)

For single - try this:

SELECT o1.*
FROM orders o1
WHERE NOT EXISTS(
    SELECT 'duplicate'
    FROM orders o2
    WHERE o1.id <> o2.id
   AND o1.buy_date = o2.buy_date
)

Having Count > 1 returns duplicates as you said. Having Count = 1 will return non duplicates.

Shouldn't it be count(*) = 1?

If you have count(*) = 0 it means that you select only those record that do not exist... so it correctly returns nothing.

Or if you want to be mathematically correct, negation of sth>1 is sth<=1

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM