2013-03-24 92 views
-1

我已經創建了SQL兩個表....SQL加入與MAX功能

1.產品

ProductId as Primary key, 
ProductName,ProductPrice 
and ProductCategoryId as Foreign Key 

這是指primary key of ProductCategory table

2.ProductCategory

CategoryId as Primary Key and CategoryName. 

我想顯示具有在每個類別最多的產品價格.....

假設有兩類..

1.Soap 
2.Shampoo. 

並在產品表中有4行...

1.Dove Soap with price 42Rs 
2.Dettol Soap with price 25Rs 
3.Dove Shampoo with price 120Rs and 
4.Sunsilk Shampoo with Price 140Rs 

然後輸出應該是這樣的....

1.Dove肥皂,價格42,類別名稱肥皂。 2.Sunnsilk洗髮水,價格140,類別名稱洗髮水。

請回復此查詢使用連接操作的sql查詢。

+1

你有沒有嘗試過的東西* *前問?也許你應該問問你的老師。 – MLeblanc 2013-03-24 19:16:05

+0

對於一個類別,是否可以有兩個相同最大值的項目?像另一種肥皂,但其價格也是42Rs?如果這是可能的,你想怎麼展示他們? – GayanSanjeewa 2013-03-25 02:55:43

回答

0

試試這個

;WITH MaxValues 
AS 
(
SELECT MAX(p.ProductPrice) MaxPrice, p.ProductCategoryId ProductCategoryId 
FROM Product p 
GROUP BY p.ProductCategoryId 
) 
SELECT p.ProductName, m.MaxPrice, c.CategoryName 
FROM MaxValues m JOIN Product p ON m.ProductCategoryId = p.ProductCategoryId 
JOIN ProductCategory c ON p.ProductCategoryId = c.CategoryId 
WHERE p.ProductPrice = m.MaxPrice