在pubs数据库中,我想查询销售质量最高的商店。 我执行以下查询,
select stores.stor_id, sum(sales.qty) as sumqty
from stores
join sales on stores.stor_id = sales.stor_id
group by stores.stor_id, stores.stor_name
结果:
+-------+------+
|stor_id|sumqty|
+-------+------+
|6380 |8 |
+-------+------+
|7066 |125 |
+-------+------+
|7067 |90 |
+-------+------+
|7131 |130 |
+-------+------+
|7896 |60 |
+-------+------+
|8042 |80 |
+-------+------+
我需要的结果就像
+-------+------+
|stor_id|sumqty|
+-------+------+
|7131 |130 |
+-------+------+
你能提出一些建议吗? 感谢。
答案 0 :(得分:1)
简单来说,使用SELECT TOP 1
和ORDER BY DESC
select top 1 sales.stor_id, sum(sales.qty) as sumqty
from stores
join sales on stores.stor_id = sales.stor_id
group by sales.stor_id
order by 2 desc;
无论如何,为什么你需要加入stores
?我认为从sales
表就足够了:
select top 1 sales.stor_id, sum(sales.qty) as sumqty
from sales
group by sales.stor_id
order by 2 desc;
如果结果有两个或多个记录作为最大值,则上述查询将失败。
用它来处理:
select sales.stor_id, MAX(sumqty) as sumqty from (select sales.stor_id, sum(sales.qty) as sumqty
from sales
group by sales.stor_id) sales
答案 1 :(得分:0)
Select a.stor_id, max(sumqty)
From (
select sales.stor_id, sum(sales.qty) as sumqty
from stores
join sales on stores.stor_id = sales.stor_id
group by sales.stor_id
) a
Group by a.stor_id
以防您有两个销售数量相同的商店