SQL查询:获取2011年每月订购的最昂贵的产品

时间:2011-10-25 17:34:43

标签: mysql sql database

我不明白如何“组合”两个表,以便我可以为此生成答案。

基本上我有一个CAP数据库,我只关心两个表:

ORDERS (ordno, month, year, cid, aid, pid, qty, dollars)
PRODUCTS (pid, pname, city, quantity, price)

我知道我需要生成一个如下所示的新表来获得答案:

Temp (month, year, pname, price)

我尝试这样做的方式是:

Temp = Select * from (

(Select month, year from Orders)

join

(Select price, pname from Products)

on

orders.pid = products.pid )

上面的查询给出了一个我不理解的错误:每个派生表都必须有自己的别名。

下一步我很确定:

Answer = select max(price), pname, month from Temp where year = 2011 group by month;

我对SQL很新。如果你们能帮助我那会很棒。如果有一个网站可以帮助我更好地学习SQL,请告诉我。谢谢!

编辑:如果有多个产品具有最高价格,那么您需要列出该月的所有产品。

编辑2:已经解决了!!

3 个答案:

答案 0 :(得分:0)

这看起来就像你想要做的那样:

SELECT o.month, o.year, p.price, p.pname
from orders o 
INNER JOIN products p on p.pid = o.pid
INNER JOIN (
    select o.month, o.year, max(p.price) price 
    from orders o 
    left outer join products p on p.pid = o.pid
    group by o.month, o.year
) maxInfo ON (o.month = maxInfo.month) and (o.year = maxInfo.year) and (p.price = maxInfo.price)

答案 1 :(得分:-1)

修改

如果产品价格发生变化,您将无法获得有意义的结果。

SELECT P.pid, P.price, O.month, P.pname FROM 
products as P
JOIN orders AS O ON
    P.pid = O.pid       
JOIN (
    SELECT
        MAX(P.price) AS price
        , O.month           
    FROM
        orders AS O
        LEFT JOIN products AS P ON
            O.pid = P.pid
    WHERE
        O.year = 2011
    GROUP BY
        O.month
) AS MX ON
    MX.month = O.month
    AND O.year = 2011
    AND P.price = MX.price

FYI这是您为派生表提供别名的方法。

(Select month, year from Orders) AS myAlias

答案 2 :(得分:-1)

错误是因为您的建筑物的子表没有别名。我相信你的错误的答案将被解决:

Temp = Select * from (  
(Select month, year from Orders)ords
join  
(Select price, pname from Products)prods  
on  ords.pid = prods.pid )

您正在构建一个表格,然后将其别名化为ords或prods。