1

这是一个家庭作业,但我不能一个人做。

1) 列出代号、销售汽车数量和转售利润总额,对利润不超过 5000 美元的转售。

resale:
cod | name    | city      | state
--------+-----------------+------------+--------
01  | Paraiso | Sao Paulo | SP
02  | Alameda | Taubate   | SP
03  | Cabana  | Macae     | RJ
04  | Santana | Betim     | MG


Automotive:
cod | manufacturer | model      | year | country   | price
--------+------------+-----------------+------+-----------+----------
01  | 01           | Gol        | 2000 | Brasil    | 25000.00
02  | 01           | Golf       | 2005 | Argentina | 39000.00
03  | 04           | Ford Ka    | 1990 | Brasil    | 15000.00
04  | 03           | Corsa Seda | 1995 | Brasil    | 12500.00
05  | 04           | Fiesta     | 2003 | Argentina | 20000.00
06  | 03           | Corsa Seda | 1995 | Argentina | 10000.00
07  | 05           | Palio      | 2002 | Brasil    | 15000.00
08  | 05           | Siena      | 2006 | Brasil    | 26000.00

sale:
customer| resale | automotive | date       | value
---------+---------+-----------+------------+----------
02      | 01     | 03         | 2010-02-05 | 17500.00
04      | 02     | 01         | 2010-01-07 | 28000.00
01      | 03     | 08         | 2010-02-15 | 28000.00
02      | 03     | 02         | 2010-03-12 | 42000.00
03      | 04     | 06         | 2010-02-06 | 11500.00
03      | 02     | 05         | 2010-01-25 | 22100.00
01      | 01     | 04         | 2010-01-21 | 15500.00
03      | 01     | 08         | 2012-02-05 | 17500.00

我的 SQL:

SELECT automotive.cod, resale.name, COUNT(sale.resale) AS ammount, SUM(sale.value - automotive.price) AS total FROM sale, automotive, resale 
WHERE sale.resale = resale.cod AND automotive.cod = sale.automotive 
GROUP BY sale.resale, automotive.cod, resale.name 
HAVING SUM(sale.value - automotive.price) <= 5000;

我不能一个人做,我的答案是错误的。

ps:我正在使用 PostgresSQL。

4

1 回答 1

2

你几乎拥有它:

SELECT r.cod, r.name
     , count(s.resale) AS amount
     , sum(s.value - a.price) AS total
FROM   sale s
JOIN   automotive a ON a.cod = s.automotive 
JOIN   resale r     ON r.cod = s.resale
GROUP  BY r.cod, r.name 
HAVING sum(s.value - a.price) <= 5000;

我使用表别名和显式JOIN语法重新格式化了您的查询,以使其更具可读性。

基本上,您只需要替换a.codr.cod. 看起来像一个错字。这使得s.resaleGROUP BY子句变得多余,因此我将其删除。

于 2012-05-27T19:08:36.563 回答