我编写了以下查询,该查询计算每个客户的订阅“类型”,并显示订阅名称以及与之关联的客户数量。它有效。
例如:
订阅A = 200个客户 订阅B = 57
select
subscription_name, count(subscription_name) as Num_of_Customers
from
subscription
join customer on subscription.subscription_number=customer.subscription_number
group by subscription_name;
我无法弄清楚如何显示“ONLY”具有最多客户数量的订阅名称。
我非常感谢你的建议。感谢。
答案 0 :(得分:1)
您可以按客户数量排序结果,并将结果限制在第一行:
您没有提到您正在使用的DBMS,并且在不同系统中这样做的方式不同:
MYSQL - 在LIMIT 1
后使用ORDER BY
:
select subscription_name, count(subscription_name) as Num_of_Customers
from subscription
join customer on subscription.subscription_number = customer.subscription_number
group by subscription_name
order by count(subscription_name) desc
limit 1;
SQL-SERVER - 使用SELECT TOP 1
select top 1 subscription_name, count(subscription_name) as Num_of_Customers
from subscription
join customer on subscription.subscription_number = customer.subscription_number
group by subscription_name
order by count(subscription_name) desc;
Oracle - 使用ROWNUM
select * from
( select subscription_name, count(subscription_name) as Num_of_Customers
from subscription
join customer on subscription.subscription_number = customer.subscription_number
group by subscription_name
order by count(subscription_name) desc
) a
where ROWNUM = 1;
如果您正在使用其他DBMS,您也可以看到如何做到这一点的想法。