简体   繁体   中英

How can I count the number of rows in the last day?

Here is my table structure:

// refund_requests
+----+---------+------+------------+
| id | user_id | paid | date_time  |
+----+---------+------+------------+
| 1  | 123     | 1    | 1498830938 |
| 2  | 456     | 0    | 1498830939 |
| 3  | 123     | 0    | 1498830940 |
+----+---------+------+------------+

I need to get two thigs:

  1. The number of registered refund requests in the last day for a specific user.
  2. The paid value of the last registered refund request for a specific user.

So the expected result is: (for user user_id = 123 )

+---------------------------------+--------------------------------+
| refund_requests_num_in_last_day | paid_value_of_the_last_request |
+---------------------------------+--------------------------------+
| 2                               | 0                              |
+---------------------------------+--------------------------------+

Any idea how can I get that in MySQL ?


Here is my current query:

SELECT COALESCE(sum(date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1  DAY))),0) AS refund_requests_num_in_last_day,
       paid AS paid_value_of_the_last_request
FROM refund_requests
WHERE user_id = 123

My query doesn't guarantee the value of paid belongs to the last row (the one which the has biggest id)

select (select count(`id`) from refund_requests where user_id = 123
and date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 DAY))
) as refund_requests_num_in_last_day,
(select paid from refund_requests where user_id = 123
and date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 DAY))
order by `id` desc limit 1
) as paid_value_of_the_last_request

You could get the last value of paid column in another clause like

SELECT COUNT(*) AS refund_requests_num_in_last_day,
       t.paid AS paid_value_of_the_last_request
FROM refund_requests
CROSS JOIN(
    SELECT paid
    FROM refund_requests
    WHERE FROM_UNIXTIME(date_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1  DAY), '%Y-%m-%d')
    AND user_id = 123
    ORDER BY id DESC
    LIMIT 1
) t
WHERE user_id = 123
AND FROM_UNIXTIME(date_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1  DAY), '%Y-%m-%d')

Another way by using string functions

SELECT COUNT(*) AS refund_requests_num_in_last_day,
       SUBSTRING_INDEX(GROUP_CONCAT(paid ORDER BY id DESC),',',1) AS paid_value_of_the_last_request
FROM refund_requests
WHERE user_id = 123
AND FROM_UNIXTIME(date_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1  DAY), '%Y-%m-%d')

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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