dro80463 2017-08-25 07:17
浏览 437
已采纳

从2个不同日期获取数据并进行比较

I have a question. So I have this data in array :

id      idm         amount           date
1        5          10              2017-08-23 12:12:12
2        5          20              2017-08-23 12:14:16
3        6          13              2017-08-23 18:00:00
4        5          25              2017-08-24 19:00:00
5        5          160             2017-08-24 19:30:00

So the idea is to get the sum of amount from date 2017-08-23 and compare with date 2017-08-24. If difference between those 2 values for a user is bigger than 20 for example in this case I found a user.

My propose was to make 2 sql's :

select sum(amount) as previous_amount, idm 
FROM table
WHERE date >= '2017-08-23 00:00:00' AND date <= '2017-08-23 23:59:59' 
GROUP By idm

select sum(amount) as actual_amount, idm 
FROM table
WHERE date >= '2017-08-24 00:00:00' AND date <= '2017-08-24 23:59:59' 
GROUP By idm

And make the treatment in php, but maybe exist a methode to do that in sql. Can you help me please ? Thx in advance and sorry for my english.

  • 写回答

4条回答 默认 最新

  • doushi8187 2017-08-25 07:44
    关注

    If I correctly understand, this is what you want:

    select 
    idm,
    sum(case when date >= '2017-08-23 00:00:00' AND date <= '2017-08-23 23:59:59' then amount end)  -
    sum(case when date >= '2017-08-24 00:00:00' AND date <= '2017-08-24 23:59:59' then amount end)  as diff
    from your_table
    group by idm
    having diff not between -20 and 20
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿