Question

In pubs database, I want to query the store in which has highest sales quality. I exec following query,

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

Results:

+-------+------+
|stor_id|sumqty|
+-------+------+
|6380   |8     |
+-------+------+
|7066   |125   |
+-------+------+
|7067   |90    |
+-------+------+
|7131   |130   |
+-------+------+
|7896   |60    |
+-------+------+
|8042   |80    |
+-------+------+

The result I need is like

+-------+------+
|stor_id|sumqty|
+-------+------+
|7131   |130   |
+-------+------+

Could you give some suggestions? Thanks.

No correct solution

OTHER TIPS

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

Just in case you have two stores with the same sales qty

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top