Reputation: 87
Suppose i have the following table:
transactions(id, type)
id
- id of the costumer (integer 1...n)
type
- what they bought (like "apple")
Note that each row refers to buying only ONE of the given type.
How can I select the id of the costumer who bought the most of a given type (like apple)?
I tried to COUNT()
the rows where type = apple for each id, but I cannot use MAX()
in that query to select only the first ID.
Thanks
Upvotes: 0
Views: 1453
Reputation: 476624
You can first make a query that for every customer counts the amount of times he bought an 'apple'
, with:
SELECT id,COUNT(*) AS total
FROM transactions
WHERE type = 'apple'
GROUP BY id
Now we only need to ORDER BY
that total
in DESC
ending order, and return the first row with FETCH FIRST n ROWS ONLY
, like:
SELECT id,COUNT(*) AS total
FROM transactions
WHERE type = 'apple'
GROUP BY id
ORDER BY total DESC
FETCH FIRST 1 ROWS ONLY
Upvotes: 1
Reputation: 94914
As you are asking for Oracle in particular: STATS_MODE
gives you the value that occurs most often.
select stats_mode(id)
from transactions
where type = 'apple';
Upvotes: 0
Reputation: 1123
This is SQL 101, you should read about group by
clause:
select id,
count(*) as count_of_apples
from transactions
where type = 'apple'
group by id
order by count(*) desc
Upvotes: 0