2010-06-23 63 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