代码之家  ›  专栏  ›  技术社区  ›  Rasmus

在SQL中查找价格高低

  •  1
  • Rasmus  · 技术社区  · 14 年前

    在这个示例数据库中,有两个表:产品和价格。 目标是找到每种产品的最高和最低价格。

    价格表每个产品可以有零行、一行或两行。

    create table products(
        id int,
        name nvarchar(50)
    )
    
    create table prices(
        productId int,
        price int
    )
    
    insert into products (id, name) values (33,'bike')
    insert into products (id, name) values (44,'car')
    insert into products (id, name) values (55,'bus')
    
    insert into prices (productId, price) values (33, 10)
    insert into prices (productId, price) values (33, 40)
    insert into prices (productId, price) values (44, 300)
    

    SQL查询应产生以下结果:

    productId  highPrice  lowPrice
    33         40         10
    44         300        NULL
    55         NULL       NULL
    
    3 回复  |  直到 14 年前
        1
  •  1
  •   Yellowfog    14 年前

    这为您提供了在SQL Server 2005中要查找的表(我注意到其他答案没有)。

    select P.ID as ProductID, 
    nullif(sum(case when idx=1 then price else 0 end), 0) as highPrice,
    nullif(sum(case when idx=2 then price else 0 end), 0) as lowPrice  from
    (
        select productid, price, row_number() over(partition by productID order by price desc) as idx from prices
    ) T
    right join products P on T.productID = P.ID
    group by P.ID
    
        2
  •  4
  •   simendsjo    14 年前

    这是针对MySQL的,但也可能适用于您。

    SELECT
    products.id as productId
    , MIN(price) as highPrice
    , MAX(price) as lowPrice
    FROM products
      LEFT JOIN prices ON products.id=prices.productId
    GROUP BY products.id
    
        3
  •  4
  •   Miles    14 年前
    SELECT productId,
            MAX(price) AS highPrice,
            MIN(price) AS lowPrice
    FROM prices
    GROUP BY productId
    

    如果你也想要产品名:

    SELECT name,
            MAX(price) AS highPrice,
            MIN(price) AS lowPrice
    FROM products
        LEFT OUTER JOIN prices ON ID = ProductID
    GROUP BY name