2010-06-23 37 views
1

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

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

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 

回答

1

这给了你,你要查找的表(我注意到其他答案不用),在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 
+0

谢谢,只是我一直在寻找的结果 – Rasmus 2010-06-24 07:52:37

4
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 
+0

但是,这并没有给用户表他说他以后的结果。我们确定他写的是什么? – Yellowfog 2010-06-23 20:10:32

+0

我怀疑Simdendsjo犯了一个错误。我只是展示了如何使用函数中的MAX和MIN来解决这个问题。如果您运行我的第二个查询并将“name”替换为“id”,那么您将得到与该问题完全相同的结果集。 – Miles 2010-06-23 20:36:12

+0

男孩,为什么我没有看到这个简单的解决方案。 – Rasmus 2010-06-24 07:52:12

4

这是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