在另一个值相同的行中选择最大值

时间:2013-05-22 12:11:26

标签: sql postgresql

很抱歉,如果主题名称看起来令人困惑 - 我无法想出更好的方式来表达它。

我坚持使用SELECT语句。我有一个包含3个表格的数据库:

Customer (PK cid, name, city, gender); 
Goods (PK gid, name, price, available[bool]); 
Sales (PK sid, FK cid, FK gid, count, discount, sdate) 

我要做的是找到每个城市销售商品的最大折扣。

所以,如果城市和折扣的选择如下:

city               | discount
-------------------+---------
TARDIS             | 0.1
London             |
London             | 0.05
Boeshane Peninsula | 0.15
London             | 0.1
London             | 0.05

我想得到的是:

city               | MaxDiscount
-------------------+----------
Boeshane Peninsula | 0.15
London             | 0.1
TARDIS             | 0.1

而且我不确定如何按城市分组并在结果中找到最大折扣。我最接近的是SELECT city, (SELECT max(discount) FROM Sales, Customer GROUP BY city) as MaxDiscount FROM Sales, Customer ORDER BY city;,但它不起作用,因为它试图将多行插入一行。

2 个答案:

答案 0 :(得分:4)

select city, max(discount) as MaxDiscount 
from customer, sales, goods
where customer.cid = sales.cid
  and goods.gid = sales.gid
group by city

答案 1 :(得分:4)

select city,max(discount) as MaxDiscount

from Customer cu

inner join Goods Go on cu.cid = Go.gid
inner join Sales  Sa on cu.cid = Sa.sid
where cu.city like 'XYZ%'

group by city,discount

或者:

select city,max(discount) as MaxDiscount

from Customer cu

inner join Sales  Sa on cu.cid = Sa.sid
where cu.city like 'XYZ%'

group by city,discount
相关问题