简体   繁体   English

MySQL按日期获取最接近的值

[英]MySQL get nearest value by date

I have following table where I store the customer counts every week 我有下表存储每周的客户数量

| area    | date       | count |
|---------|------------|-------|
| AREA I  | 2016-03-20 | 530   |
| AREA I  | 2016-03-13 | 520   |
| AREA II | 2016-03-20 | 370   |

Now I want to get the nearest customer count by date value at another table. 现在,我想在另一个表上按日期值获取最近的客户数。 So if I give f.ex. 所以,如果我给f.ex。 date 2016-03-15 it should return 520 for AREA I and 370 for AREA II . 日期为2016-03-15 ,对于AREA I ,应该返回520,对AREA II ,应该返回370。

Example query: 查询示例:

SELECT a.period, a.area, b.customerCount FROM periods a
JOIN customer_count b ON (...)
GROUP BY a.period, a.area

I think that I should be using ABS() and DATEDIFF() somehow but I didn't get that. 我认为我应该以某种方式使用ABS()DATEDIFF()但我没有得到。 Or is there some other way to do this? 还是有其他方法可以做到这一点?

Thanks in advance. 提前致谢。

Try to use: 尝试使用:

SELECT a.period, a.area, b.customerCount FROM periods a
JOIN customer_count b ON (...)
GROUP BY a.period, a.area
ORDER BY ABS(DATEDIFF( `date`, NOW()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM