3

抱歉,如果主题名称看起来令人困惑——我想不出更好的表达方式。

我坚持使用 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;,但它不起作用,因为它试图将几行插入一行。

4

2 回答 2

4
select city, max(discount) as MaxDiscount 
from customer, sales, goods
where customer.cid = sales.cid
  and goods.gid = sales.gid
group by city
于 2013-05-22T12:24:04.473 回答
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
于 2013-05-22T12:25:15.433 回答