我有一个典型的products
表,其中包含字段name
和price
。我必须选择所有价格的总和、最便宜产品的名称和最昂贵产品的名称,然后将其全部返回到同一结果集中。我尝试了一些组合,但我能想到的最好的方法是带有多个嵌套子选择的丑陋查询。谁能帮我提供一个好的查询示例吗?提前致谢。
为了说明问题,这里有一个简约的产品
表:
+----+-------+------------------+
| id | price | name |
+----+-------+------------------+
| 1 | 2.20 | Shack Beer |
| 2 | 3.40 | Freeze IPA |
| 3 | 1.10 | Poor Man's Ale |
| 4 | 3.40 | Alabama Sour |
| 5 | 7.20 | Irish Stout |
+----+-------+------------------+
根据上表,查询必须返回以下结果集:
total_pricing = 17.30
cheapest_product = Poor Man's Ale
most_expensive_product = Irish Stout
最佳答案
这里有几个选项供您选择 ( SQL Fiddle ):
SELECT SUM(p.price) AS total_pricing,
(
SELECT name
FROM products
ORDER BY price
LIMIT 1
)AS cheapest_product,
(
SELECT name
FROM products
ORDER BY price DESC
LIMIT 1
)AS most_expensive_product
FROM products p;
或者在单独的行中:
SELECT 'total_pricing' as Category, SUM(p.price) AS total_pricing
FROM products p
UNION
(
SELECT 'cheapest_product', name
FROM products
ORDER BY price
LIMIT 1
)
UNION
(
SELECT 'most_expensive_product', name
FROM products
ORDER BY price DESC
LIMIT 1
);
关于mysql - 根据聚合结果选择字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623102/