[英]calculate the min of a table grouped by a unique id - mysql
I need a help with a query. 我需要查询方面的帮助。
select *,min(cast(hour(now())- hour_offer) as unsigned)) as time_left
from out_of_offer
group by offer_id
order by time_left asc
I have multiple hour_offer in my out_of_offer table and I need to get only one record (grouped by offer_id) that is closest to the current hour. 我的out_of_offer表中有多个hour_offer,我只需要获取一个最接近当前小时的记录(按offer_id分组)。
for example 例如
offer_id hour(now()) hour_offer
1 11 8
2 11 9
1 11 10
2 11 11
2 11 12
what I want my query to do is to get the 3rd and 4th rows because they are the closest to the current hour (11) and they have different offer_ids. 我希望查询执行的操作是获取第三行和第四行,因为它们最接近当前小时(11),并且它们具有不同的offer_id。
hour_offer is mediumint(2) unsigned
can anybody help me how to do that? 有人可以帮我怎么做吗?
EDIT if I print out hour(now())-hour_offer
in the mysql query the result is an huge (positive) number. 编辑如果我打印出
hour(now())-hour_offer
在MySQL查询结果是一个巨大的(正)号。
Try something like this: 尝试这样的事情:
SELECT * FROM out_of_offer o,
(SELECT offer_id, MIN(ABS(hour-hour_offer)) AS diff FROM out_of_offer
GROUP BY offer_id) x
WHERE o.offer_id = x.offer_id AND ABS(o.hour-o.hour_offer) = x.diff;
I guess is better use ABS
isntead of CAST
. 我想最好使用
CAST
ABS
istead。 I don't know exactly why, but your syntax on CAST
is wrong. 我不知道为什么,但是您在
CAST
上的语法是错误的。
You may change de hour
for hour(now)
. 您可以将de
hour
更改为hour(now)
。 I used hour
to test the query on SQLFiddle. 我用了一个
hour
来测试SQLFiddle上的查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.