通过id得到最新组的总和

时间:2015-09-04 20:07:26

标签: mysql

我很难获得独特书籍的最新价值

这个表看起来像

book_id     ordered_at(unix timestamp)                                  value
1           1440630635 - assume this is July 1, 2015 8:00:00                    250
1           1440630635 - assume this is July 15, 2015 8:00:00                     150
1           1440630635 - assume this is July 30, 2015 8:00:00                     100
2           1440630635- assume this is July 5, 2015 8:00:00                       200
2           1440630635- assume this is July 20, 2015 8:00:00                      300
2           1440630635- assume this is July 30, 2015 8:00:00                      200

给定时间戳,我想按书获得最近订单的总价值

表示,如果给定的时间戳 2015年7月31日00:00:00

查询应返回总和值300,因为7月30日是书1和2的最新值

1           1440630635 - assume this is July 30, 2015 8:00:00                     100
2           1440630635- assume this is July 30, 2015 8:00:00                      200

如果给定时间戳 2015年7月22日00:00:00

查询应返回450的总和值,因为7月15日是图书1的最新版本,7月20日是图书2的最新版本

1           1440630635 - assume this is July 15, 2015 8:00:00                     150
2           1440630635- assume this is July 20, 2015 8:00:00                      300

编辑:我只是在寻找最近和最少的日期

1 个答案:

答案 0 :(得分:2)

您可以在子查询中进行聚合,以便在上述日期(7月22日或7月31日或其他日期)之前找出每本图书的最长日期。只汇总与子查询匹配的记录

-- your table structure may be different. This example serves just as a guide
create table test (
  book_id int,
  ordered_at datetime,
  book_value int
);

insert into test values 
(1, '2015-07-01 08:00:00', 250),
(1, '2015-07-15 08:00:00', 150),
(1, '2015-07-30 08:00:00', 100),
(2, '2015-07-05 08:00:00', 200),
(2, '2015-07-20 08:00:00', 300),
(2, '2015-07-30 08:00:00', 200);

-- Result of this will be 450
select sum(book_value) 
from test a 
inner join 
-- sub-query that gets the latest data for each book
(
    select book_id, max(ordered_at) max_ordered_at 
    from test 
    where ordered_at < '2015-07-22 00:00:00'
    group by book_id
) b 
    on a.book_id = b.book_id and a.ordered_at = b.max_ordered_at;

如果日期更改为&#39; 2015-07-31 00:00:00&#39;,则结果应为300。

如果希望找到最接近给定日期的总计,则可以使用此查询:

-- Result: 450
select sum(book_value) 
from test a 
inner join 
(
    select book_id
          ,min(abs(unix_timestamp(ordered_at) - unix_timestamp('2015-07-22 00:00:00'))) as latest 
    from test 
    group by book_id
) b 
    on a.book_id = b.book_id 
    and abs(unix_timestamp(a.ordered_at) - unix_timestamp('2015-07-22 00:00:00')) = b.latest;