首先,我认为你想要的sum
是股票,而不是count
它们。
问题是您的查询正在尝试一次执行两个级别的聚合(首先对份额进行计数/求和,然后取其中的最大值),这是不可能的。
尝试这个:
select c.name
, count(t.shares) as "Number of trades"
, sum(t.shares) as "Trade volume"
from trade t
join company c on c.stock_id = t.stock_id
group by c.name
order by sum(t.shares) desc
fetch first row only;
(该fetch first
子句需要 Oracle 12.1 或更高版本。)
或这个:
select name, total_shares
from ( select c.name
, sum(t.shares) as total_shares
, rank() over (order by sum(t.shares) desc) as ranking
from trade t
join company c on c.stock_id = t.stock_id
group by c.name )
where ranking = 1;
样本数据:
create table company
( stock_id number primary key
, name varchar2(30) not null );
create table trade
( stock_id references company
, shares number not null );
insert all
into company values (1, 'Apple')
into company values (2, 'Microsoft')
into company values (3, 'Oracle')
into company values (4, 'Huawei')
into company values (5, 'Robertson Solutions')
select * from dual;
insert all
into trade values (1, 10)
into trade values (2, 5)
into trade values (3, 100)
into trade values (4, 200)
into trade values (5, 5)
into trade values (1, 20)
into trade values (2, 30)
into trade values (3, 40)
into trade values (4, 50)
into trade values (5, 20)
into trade values (1, 70)
select * from dual;
汇总数据:
select c.name
, sum(t.shares) as total_shares
, rank() over (order by sum(t.shares) desc) as ranking
from trade t
join company c on c.stock_id = t.stock_id
group by c.name
order by total_shares desc;
NAME TOTAL_SHARES RANKING
-------------------- ------------ ----------
Huawei 250 1
Oracle 140 2
Apple 100 3
Microsoft 35 4
Robertson Solutions 25 5