[英]How to use MAX() and COUNT() in Oracle SQL?
Suppose i have the following table: 假设我有下表:
transactions(id, type)
交易(编号,类型)
id
- id of the costumer (integer 1...n)id
-负荷消费(整数1 ... N)的ID
type
- what they bought (like "apple")type
-他们买了什么(例如“苹果”)
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)? 如何选择购买了给定类型(例如苹果)最多的顾客的ID?
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. 我尝试对每个id进行
COUNT()
其中类型= apple的行COUNT()
,但是无法在该查询中使用MAX()
仅选择第一个ID。
Thanks 谢谢
You can first make a query that for every customer counts the amount of times he bought an 'apple'
, with: 您可以首先进行查询,以查询每个客户购买
'apple'
的次数:
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: 现在,我们只需
DESC
结束顺序对该total
进行ORDER BY
,并返回FETCH FIRST n ROWS ONLY
的第一行 ,例如:
SELECT id,COUNT(*) AS total
FROM transactions
WHERE type = 'apple'
GROUP BY id
ORDER BY total DESC FETCH FIRST 1 ROWS ONLY
This is SQL 101, you should read about group by
clause: 这是SQL 101,您应该阅读有关
group by
子句的信息:
select id,
count(*) as count_of_apples
from transactions
where type = 'apple'
group by id
order by count(*) desc
As you are asking for Oracle in particular: STATS_MODE
gives you the value that occurs most often. 当您特别要求Oracle时:
STATS_MODE
为您提供最常出现的值。
select stats_mode(id)
from transactions
where type = 'apple';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.