2013-03-24 69 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