SQL查询以获取列的最大值并显示每行
这是我的场景。。。 多个项目具有多个价格的多个项目类型。 要选择显示最高价格的所有类型的项目。想不出如何获得最大值 输入:SQL查询以获取列的最大值并显示每行,sql,sql-server,Sql,Sql Server,这是我的场景。。。 多个项目具有多个价格的多个项目类型。 要选择显示最高价格的所有类型的项目。想不出如何获得最大值 输入: ProductId ProductType Description Price 1个烤豆1.29 1 B烤豆1.98 输出: ProductId ProductType Description Price 1个烤豆1.98 1 B烤豆1.98 有什么建议吗 Select ProductId, ProductType, Description, M
ProductId ProductType Description Price
1个烤豆1.29
1 B烤豆1.98
输出:
ProductId ProductType Description Price
1个烤豆1.98
1 B烤豆1.98
有什么建议吗
Select ProductId, ProductType, Description, MaxByDesc.MaxPrice
From Product
Join (
Select Description, Max(Price) As MaxPrice
From Product
Group By Description
) As MaxByDesc
On MaxByDesc.Description = Product.Description
如果您使用的是SQL Server 2005或更高版本:
Select ProductId, ProductType, Description
, Max( Price ) Over ( Partition By Description ) As MaxPrice
From Product
如果您使用的是SQL Server 2005或更高版本:
Select ProductId, ProductType, Description
, Max( Price ) Over ( Partition By Description ) As MaxPrice
From Product
试试这个:
SELECT ProductId,
ProductType,
Description,
b.price
FROM <YOUR_TABLE> a,
(SELECT MAX(price) price FROM <YOUR_TABLE>) b
对于喜欢ANSI语法的人:
SELECT ProductId,
ProductType,
Description,
b.price
FROM <YOUR_TABLE> a INNER JOIN
(SELECT MAX(price) price FROM <YOUR_TABLE>) b
ON 1=1
试试这个:
SELECT ProductId,
ProductType,
Description,
b.price
FROM <YOUR_TABLE> a,
(SELECT MAX(price) price FROM <YOUR_TABLE>) b
对于喜欢ANSI语法的人:
SELECT ProductId,
ProductType,
Description,
b.price
FROM <YOUR_TABLE> a INNER JOIN
(SELECT MAX(price) price FROM <YOUR_TABLE>) b
ON 1=1
托马斯,对,除了你需要按类型分组之外:
Select ProductId, ProductType, Description, MaxByDesc.MaxPrice
From Product
Join (
Select Description, Max(Price) As MaxPrice
From Product
Group By ProductType
) As MaxByDesc
On MaxByDesc.ProductType = Product.ProductType
托马斯,对,除了你需要按类型分组之外:
Select ProductId, ProductType, Description, MaxByDesc.MaxPrice
From Product
Join (
Select Description, Max(Price) As MaxPrice
From Product
Group By ProductType
) As MaxByDesc
On MaxByDesc.ProductType = Product.ProductType
另一种方式:
SELECT ProductId
, ProductType
, Description
, ( SELECT MAX(price)
FROM Product pg
WHERE pg.Description = p.Description
) AS MaxPrice
FROM Product p
另一种方式:
SELECT ProductId
, ProductType
, Description
, ( SELECT MAX(price)
FROM Product pg
WHERE pg.Description = p.Description
) AS MaxPrice
FROM Product p
它起作用了。非常感谢!我在子查询中使用行号来获取最新价格。我不知道我可以用MAX和Partition BY…它可以用。非常感谢!我在子查询中使用行号来获取最新价格。我不知道我可以使用MAX和Partition BY…尽管我从不建议使用逗号分隔的语法。总有一天SQL Server会停止支持它,只要它能早点发生。@Thomas:用ANSII版本的Join更新了帖子。尽管如此,我永远不建议使用逗号分隔的语法。总有一天SQL Server会停止支持它,只要它能早点发生。@Thomas:用ANSII版本的join更新了帖子