MySQL-如何选择与最近日期相关联的值+所有值的最大值/最小值

时间:2019-03-28 15:38:49

标签: mysql

我的表结构看起来像这样: 1.自动生成的主键(整数) 2.名称(非唯一) 3.价值 4.日期

我想执行一个查询,该查询返回与最近日期相关联的值,以及给定特定名称的所有日期的最大值/最小值。

例如,如果我有一个像这样的表

--------------------------------
| 1 |  jack  | 2  | 2019-03-25 |
| 2 |  james | 3  | 2019-03-25 |
| 3 |  jack  | 3  | 2019-03-26 |
| 4 |  jack  | 3  | 2019-03-27 |
| 5 |  james | 10 | 2019-03-27 |
| 6 |  jack  | 5  | 2019-03-28 |
--------------------------------

然后当我使用'jack'名称查询它时,我希望结果看起来像

------------------------------
| name | current | max | min |
------------------------------
| jack |    5    |  5  |  2  |
------------------------------

在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

假设您还没有尝试过任何东西,并且您不知道从哪里开始,这是一种方法

SELECT 
    name, -- first column is the name
    value as current, -- get the value as "current"
    (
        -- here we have nested query
        SELECT
            value
        FROM
            Test AS minT -- create an alias for the table to be able to refer it in the WHERE clause
        WHERE
            minT.name = name -- filters values only for the "name" that matches the name in the main query
        ORDER BY
            value ASC -- orders them by "value ASC" since we want the smallest value
        LIMIT 1 -- get only the first result
    ) as min,
    (
        SELECT
            value
        FROM
            Test as maxT
        WHERE
            maxT.name = name
        ORDER BY
            value DESC -- same as above just in reverse order
        LIMIT 1
    ) as max
FROM
    Test
ORDER BY -- orders the results by
    DATEDIFF(NOW(), date) ASC -- the diff (subtracts in days) the current date and the one in the table
LIMIT
    1 -- and just return the first row