【问题标题】:How to select maximum value from a subquery in SQL for a results display如何从 SQL 中的子查询中选择最大值以显示结果
【发布时间】:2020-09-01 06:17:28
【问题描述】:

我需要编写一个 SQL 查询来显示七个卖家的列表 - 包含来自七个地区中每个地区的最畅销的卖家,他们以任何德国、美国或日本汽车的最高价格出售了他/她的德国、美国或日本汽车。 2016年在他/她所在地区销售的日本车。

目前,我设法获得了我需要的数据,但是当我只需要显示 7 个区域中每个最畅销产品的结果时,我就陷入了困境。

下面是我的代码:

SELECT first_name, last_name, category, car, region, selling_date, price
FROM
(SELECT first_name, last_name, cars.category, sellers.car, region, selling_date, price
FROM sellers
INNER JOIN regions ON sellers.region_id = regions.region_id
INNER JOIN cars ON sellers.car = cars.car
WHERE sellers.car = ANY (SELECT car FROM cars WHERE category = 'German' OR category ='American' OR category ='Japanese')
AND selling_date BETWEEN '2016-01-01' AND '2016-12-31'
) a 
WHERE price IN (SELECT TOP (7) MAX(price)FROM sellers GROUP BY region_id)
  • 问题是当我输入“WHERE price IN (SELECT TOP (7) MAX(price)FROM Sellers GROUP BY region_id)”时,它会从每个区域获取最大值,只返回匹配结果。

【问题讨论】:

  • 你确定你在使用 MySQL!?!

标签: mysql sql inner-join display


【解决方案1】:
SELECT 
        first_name
    ,   last_name
    ,   cars.category
    ,   sellers.car
    ,   region
    ,   selling_date
    ,   price.price 
FROM        sellers 
INNER JOIN  regions ON  regions.region_id   =       sellers.region_id
INNER JOIN  cars    ON  cars.car            =       sellers.car
                    AND cars.category       IN      ('German', 'American', 'Japanese') 
                    AND cars.selling_date   BETWEEN ('2016-01-01' AND '2016-12-31')
INNER JOIN  (
                SELECT      TOP 7 
                            seller_id                           --  asuming you have a seller_id.
                        ,   region_id                           --  if not, then go by region: delete prior line and change the ON Clause to region_id
                        ,   Price = MAX(price)
                FROM        sellers 
                GROUP BY    region_id, seller_id                -- delete seller_id if you dont have it
            )   price   ON  price.seller_id = seller.seller_id  --  change the ON Clause to region_id if no seller_id

【讨论】:

  • 谢谢 Andy3B,但这会返回一个空表。我也有seller_id。我总共有 3 张桌子 - 卖家、汽车和地区。
猜你喜欢
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-07
  • 1970-01-01
相关资源
最近更新 更多