mysql - 获取最接近按类型分组的特定日期的记录

标签 mysql date group-by records

对不起,我不能更具体,但我不知道如何在标题中描述我的问题..分别我不知道如何搜索类似的问题。

所以这是交易。我有这张记录表:

sample database table

如您所见,我有在不同月份以不同类型输入的数据。我的目标是让最后输入的金额按类型分组,这应该受日期限制。

例如:

If I specify a date 2011-03-01, the query should return 3 records with amount - 10, 20 and 30, because for type=1 the nearest inserted record to '2011-03-01' is on date 2011-01-01 with amount 10. For type=2 the nearest date to '2011-03-01' is 2011-02-01 with amount 20. And for type=3 the nearest to '2011-03-01' is the '2011-03-01' so it returns amount=30.

那么如何构造MySQL查询呢?

最佳答案

现在我只能想到一个子选择版本:

SELECT type, amount
FROM table AS t
WHERE dat = (
    SELECT MAX(dat)
    FROM table
    WHERE type=t.type
        AND dat <= '2011-03-01'
)

关于mysql - 获取最接近按类型分组的特定日期的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5565360/

相关文章:

mysql - LEFT JOIN 与表两次以获得单独的记录

php - 在 symfony 中使用 PrePersist

mysql - 我无法将 MySql 数据提供程序添加到 Visual Studio 2012

php - 将正确的链接附加到 JSON

date - 如何在 yii2 中将 JalaliDate 转换为 GregorianDate?

Mysql:选择两个日期之间的所有数据

c# - 是什么导致我的代码 : String was not recognized as a valid DateTime 出现此错误

sql - 按日期时间字段分组

mysql - 在 PHPMYADMIN 中使用 group_concat 将结果显示为 [BLOB - 3B]

php - Laravel - leftJoin 和元素引用