如何计算最后一天的行数?

时间:2018-06-13 06:36:41

标签: mysql sql

这是我的表结构:

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

我需要得到两个东西:

  1. 特定用户在最后一天注册的退款请求数。
  2. 特定用户上次注册退款请求的paid值。
  3. 所以预期结果是:(对于用户user_id = 123

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

    任何想法我怎么能在MySQL中得到它?

    这是我当前的查询:

    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
    

    我的查询不保证paid的值属于最后一行(具有最大ID的那个)

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

您可以在另一个子句中获取付费列的最后一个值,例如

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')

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

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