0

I'm trying to select 1000 customers that have placed exactly 1 order. Everything is in the Orders table.

select * from Order having count(CustomerID) = 1 limit 1000

So basically all records that have only one occurence of the CustomerID in the entire table. This returns an empty result set and there are 100,000s in the table.

1
  • Are you looking for the distinct customer ID's? What value are you trying to get? Commented Jun 30, 2011 at 12:45

5 Answers 5

4

You need to GROUP in order to (meaningfully) use the HAVING clause. The following works as expected:

SELECT
    *
FROM
    `Order`
GROUP BY
    CustomerID
HAVING
    COUNT(CustomerID) = 1
LIMIT 1000

UPDATE
Adding WHERE (see comments):

SELECT
    *
FROM
    `Order`
WHERE
    Language = 'EN'
GROUP BY
    CustomerID
HAVING
    COUNT(CustomerID) = 1
LIMIT 1000
Sign up to request clarification or add additional context in comments.

3 Comments

Works! However if I add a WHERE Language = "EN" I get a syntax error. You know why?
@stef How do you add it? ... FROM `Order` WHERE ... GROUP BY ... should work. See updated answer.
@stef Do note that WHERE is executed as a condition on the query (before aggregate functions), whereas HAVING is performed afterwards since it targets aggregated data (e.g., COUNT()).
1
SELECT * FROM `Order`
GROUP BY CustomerID 
HAVING COUNT(CustomerID) = 1 
LIMIT 1000

Comments

0

try

select count(CustomerID) as counter ,o.* from Order o
group by CustomerID having  counter  = 1  limit 1000

Comments

0

Add group by to query for correct output, e.g:

select * from Order group by CustomerID having count(CustomerID) = 1 limit 1000

Comments

0

SELECT CustomerID FROM Order GROUP BY CustomerID HAVING COUNT(*) = 1 LIMIT 1000

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.