0

在 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   |
+-------+------+

你能给一些建议吗?谢谢。

4

2 回答 2

1

Simple way, use SELECT TOP 1 and 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;

Anyway, why you need join to stores? I think from sales table is enough:

select top 1 sales.stor_id, sum(sales.qty) as sumqty
from sales
group by sales.stor_id
order by 2 desc;

Above query will fail if the result has two or more records as max value.

Use this to handle that:

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
于 2014-01-16T05:33:38.353 回答
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

以防万一您有两家销售数量相同的商店

于 2014-01-16T05:40:22.643 回答