首页 > 解决方案 > MySQL-如何使用 Group By 获取值

问题描述

+-----------------+--------+-------+
| Date(yyyy-mm-dd)| name   | price |
+-----------------+--------+-------+
|    2021-03-01   | APPLE  |    15 |
|    2021-03-01   | Orange |    10 |
|    2021-03-01   | Banana |     5 |
|    2021-03-02   | Apple  |    16 |
|    2021-03-02   | Orange |     9 |
|    2021-03-02   | Banana |     4 |
|    2021-03-03   | Apple  |    17 |
|    2021-03-03   | Orange |    11 |
|    2021-03-03   | Banana |     5 |
+-----------------+--------+-------+



    **Fruit Value**

我正在尝试获取价格每天都在上涨的水果的名称。所以输出应该是“苹果”,因为苹果在 3 月 1 日的价格是 15,3 月 2 日是 16,3 月 3 日是 17...我尝试使用 group by 解决这个问题,但我仍然不是能够解决它...请任何人给我建议。

标签: mysql

解决方案


如果你有所有日期的所有水果的价格,那么你可以这样做GROUP_CONCAT()

SELECT name
FROM tablename
GROUP BY name
HAVING COUNT(*) = COUNT(DISTINCT price) -- all prices are different
   AND GROUP_CONCAT(price ORDER BY Date) = GROUP_CONCAT(price ORDER BY price)
   -- prices ordered by date are in the same order as prices ordered ascending by price

请参阅演示


推荐阅读