【问题标题】:How to sum amount between two dates如何计算两个日期之间的金额
【发布时间】:2021-01-23 12:52:05
【问题描述】:

我有一个包含'user_id', 'amount', 'today_date' 字段的表。我只想将所有amount 分组按user_id 汇总到今天和过去6 天之间的日期。我将所有日期存储在'today_date'

我尝试过这样的事情:

date_default_timezone_set('Asia/kolkata');
$date = date('Y-m-d');
$week = date('Y-m-d', strtotime('-6 days'));

$data['this_week'] = $this->db->select('sum(amount) as total, user_id')->where("today_date BETWEEN $date AND $week")->group_by('user_id')->get('tbl_transcations')->result_array(); 

我可能缺乏 CI 语法,因为我在 2 天前就开始了。 请帮帮我。

【问题讨论】:

    标签: mysql sql codeigniter datetime where-clause


    【解决方案1】:

    您的日期范围似乎有误。这个:

    ->where("today_date BETWEEN $date AND $week")
    

    应该是:

    ->where("today_date BETWEEN '$week' AND '$date'")
    

    请注意,文字日期需要用单引号引起来。

    您可以很好地删除变量并直接在数据库中进行计算:

    ->where("today_date BETWEEN current_date - interval 6 day AND current_date")
    

    如果您的日期包含时间部分,那么使用半开间隔是更好的策略:

    ->where("today_date >= current_date - interval 6 day and today_date < current_date + interval 1 day")
    

    【讨论】:

    • 显示错误 您的 SQL 语法有错误;查看与您的 MariaDB 服务器版本相对应的手册,了解在 'day AND current_date AND 附近使用的正确语法
    • 使用第二个查询时
    • 'where 子句'中的未知列'2020-10-02' SELECT sum(amount) as total, user_id FROM tbl_transcations WHERE today_date BETWEEN 2020-10-02 AND 2020-10- 08 AND type = '0' AND txn_mode = '游戏' GROUP BY user_id
    • @BhaweshBhakar:您需要在文字日期周围加上单引号。已在答案中修复。
    • 好的,有没有办法可以将 2020-06-04 10:20:03 转换为 2020-06-04,然后在上面的代码中检查条件
    猜你喜欢
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多