根据聚合结果选择字段

时间:2014-07-08 03:11:45

标签: mysql sql

我有一个典型的products表,其中包含字段nameprice。我必须选择所有价格的总和,最便宜产品的名称和最昂贵产品的名称,然后将它们全部返回到同一结果集中。我尝试了一些组合,但我能想到的最好的是一个带有多个嵌套子选择的丑陋查询。有谁可以帮我一个好的查询示例,好吗?提前谢谢。

为了说明问题,这里有一个简约的products表:

+----+-------+------------------+
| 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

2 个答案:

答案 0 :(得分:0)

检查SQL Fiddle

SELECT DISTINCT price,
                name
FROM products AS p1,

  (SELECT MAX(price) AS `most_expensive_product`,
          MIN(price) AS `cheapest_product`
   FROM products) AS p2
WHERE p2.most_expensive_product = p1.price
  OR p2.cheapest_product = p1.price
UNION
SELECT sum(price) AS price,
       "Total_pricing" AS name
FROM products;

答案 1 :(得分:0)

以下是您的几个选项(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
);