mysql一张表多条数据返回 上个月,当月,昨天,今天的总金额应该怎么写?

mysql一张表多条数据返回 上个月,当月,昨天,今天的总金额应该怎么写?,第1张

----表名tb,日期字段dt,金额字段,amt

select sum(last_mon_amt) last_mon_amt,sum(cur_mon_amt) cur_mon_amt,sum(last_day_amt ) last_day_amt from(

select sum(amt) last_mon_amt,0 cur_mon_amt,0 last_day_amt from tb where date_format(dt, '%Y%m') = date_format(date_add(sysdate(), interval -1 month), '%Y%m') --上月合计

union all

select 0 last_mon_amt,sum(amt) cur_mon_amt,0 last_day_amt from tb where date_format(dt, '%Y%m') = date_format(sysdate(),'%Y%m') --当月合计

union all

select 0 last_mon_amt,0 cur_mon_amt,sum(amt) last_day_amt from tb where date_format(dt, '%Y%m%d') = date_format(date_add(sysdate(), interval -1 day),'%Y%m%d') --昨日合计

) tb1

Year(@time), Month(@time) 2 个函数即可。

然后用它们来组装字符串也就简单了。

CONVERT(VarChar(7), @time, 120)会得到YYYY-MM。调用。

用转成字符串,,但此时他已经不是时间类型。

CONVERT(char(7),"你的时间例",120)


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/8554741.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-17
下一篇2023-04-17

发表评论

登录后才能评论

评论列表(0条)

    保存