使用group_by选择最后一列记录

时间:2017-12-20 03:08:13

标签: mysql ruby-on-rails

我有一张这样的表:

----------------------------------
| post | page_likes | created_at |
----------------------------------
|   2  |     700    | 2017-11-02 |
----------------------------------
|   1  |     702    | 2017-11-03 |
----------------------------------
|   4  |     709    | 2017-11-04 |
----------------------------------
|   2  |     712    | 2017-11-05 |
----------------------------------
|   0  |     710    | 2017-11-06 |

一个计算数据并将其用于我的图表的查询

SELECT DATE_FORMAT(created_at, '%Y%m') as ymd_id,
                  page_likes AS page_likes,
                  sum(post) AS total_posts

                  FROM table
                    Where created_at BETWEEN '2017-11-02 00:00:00' AND '2017-11-6 00:00:00'
                  GROUP BY ymd_id
                  ORDER BY ymd_id ASC

结果:

---------------------------------------
|total_posts| page_likes |   ymd_id   |
---------------------------------------
|     9     |     700    |   201711   |
---------------------------------------

page_like出错了。它需要700,但我想要的值是710.

有没有办法修改上面的查询以获取page_like的最后一行?

3 个答案:

答案 0 :(得分:2)

SELECT tt.ymd_id, test.page_likes, tt.total_posts FROM (
    SELECT DATE_FORMAT(created_at, '%Y%m') as ymd_id, MAX(created_at) as created_at, sum(post) AS total_posts
    FROM test
    Where created_at BETWEEN '2017-11-02 00:00:00' AND '2017-11-6 00:00:00'
    GROUP BY ymd_id
    ORDER BY ymd_id ASC) as tt 
join test on test.created_at = tt.created_at

SQL FIDDLE

http://sqlfiddle.com/#!9/b66e02/20

答案 1 :(得分:1)

尝试使用

select max(page_likes) as page_likes
选择块中的

答案 2 :(得分:1)

使用字符串函数的另一种方法

SELECT 
  DATE_FORMAT(created_at, '%Y%m') AS ymd_id,
  SUBSTRING_INDEX(GROUP_CONCAT(page_likes ORDER BY created_at DESC),',',1) AS page_likes,
  SUM(post) AS total_posts 
FROM
  demo 
WHERE created_at >= '2017-11-02 00:00:00' 
  AND created_at <= '2017-11-6 00:00:00' 
GROUP BY ymd_id 
ORDER BY ymd_id ASC 

DEMO