为了简单起见,我在网上找到了一个教程并切中要害:http://www.tizag.com/mysqlTutorial/mysqlmax.php
SELECT type, MAX(price) FROM products GROUP BY type
我的问题是: 我如何回显哪种“衣服”最贵(在本例中为“衬衫”)?
更新:
对不起大家,是我的错。我需要让自己更清楚。我正在寻找的是一个解决方案,显示每个“名称”最昂贵的地方:
name type price
Clothing Blouse 34.97
Toy Playstation 89.95
Music Country Tunes 21.55
尝试以下查询:
解决方案#1:
SELECT
products.name,
products.type,
products.price
FROM products
INNER JOIN
(
SELECT type,MAX(price) max_price
FROM products
GROUP BY type ) t
ON products.type = t.type
AND products.price = t.max_price;
解决方案#2:
SELECT
products.name,
products.type,
products.price
FROM
products
WHERE (type, price) IN (
SELECT type, MAX(price) max_price
FROM products
GROUP BY type )
编辑:
注意: 如果两种解决方案共享相同的
type
价格,则它们可能会为您提供相同 maximum
下的多种产品。
如果您严格想要每种类型中的至多一个项目,那么您需要在最后一行再次
group by
。
因此对于这两种解决方案,最后一行都是:
GROUP BY products.type, products.price
试试这个
select *
from product where
price=(select max(price)
from product where type='Clothing')
这将选择服装类型中价格最高的整行
然后,这将按价格降序排列商品(从最贵的开始),然后仅显示第一个商品...
SELECT name, MAX(price)
FROM products
WHERE type = 'Clothing'
ORDER BY price DESC
LIMIT 1
您只需按价格下单即可找到最昂贵(最高价值)的服装,并将记录数量限制为1。
SELECT name
FROM products
WHERE type = 'Clothing'
ORDER BY price DESC
LIMIT 1
编辑:
正如 Matt 提到的,如果不止一种产品的价格最贵,而您想要全部。您应该包含一个子查询来获取多个。
SELECT name
FROM products
WHERE type = 'Clothing'
AND price = (SELECT MAX(price)
FROM products
WHERE type = 'Clothing')
通过此查询,您可以查看所有关系,而不仅仅是服装
SELECT maxPricesPerType.type,maxPricesPerType.maxPrice,priceTypes.name
FROM
(
SELECT type, MAX(price) maxPrice FROM products GROUP BY type
) maxPricesPerType
INNER JOIN
(
SELECT type, price,name FROM products GROUP BY type,price
) priceTypes
ON priceTypes.type = maxPricesPerType.type
AND priceTypes.price = maxPricesPerType.maxPrice
这会将您的第一个数组与具有唯一价格类型组合的数组连接起来,并显示您询问的每种类型的最高价格名称。
在bigquery中,它只允许匹配WHERE子句中的一个变量。感谢您的精彩解释!
SELECT
name,
type,
price
FROM
products
WHERE (price) IN (
SELECT MAX(price) max_price
FROM products
GROUP BY type)
对于 SQL Server,但在其他 SQL 方言中肯定也有类似的情况:
select top 1 with ties
row_number() over (partition by type order by price desc)
, *
from products
order by 1