【问题标题】:Sql: How to get the total monthly income and expenses for a certain yearSql:如何获取某年的月收入和支出总额
【发布时间】:2021-12-06 02:22:19
【问题描述】:

这是表格记录:

id    date         type       amount
1     2020-08-03   income     88
2     2020-09-11   spending   -120
3     2020-09-16   income     200
4     2020-11-05   income     95
5     2020-11-30   spending   35

如何获取当年的月度统计数据?

例如:

{
   "2021-11": {income: 500, spending: -800}
   "2021-10": {income: 200, spending: -500}
   "2021-09": {income: 800, spending: -300}
   "2021-08": {income: 900, spending: -200}
}

ps: Sqlite

【问题讨论】:

  • 不要标记垃圾邮件;在标记 RDBMS 时,只需标记您真正使用的那个,而不是 3 个完全不同的。
  • 列日期数据类型?
  • 预期结果真的与样本数据相符吗?!?
  • @Larnu,不是 OP 添加了所有这些标签...
  • 你说得对,我没有注意到 @jarlh 。我太习惯低代表用户标记垃圾邮件了;不是应该知道更好地在编辑中添加标签垃圾邮件的人。

标签: sql sqlite


【解决方案1】:

可以在 sum group 函数中使用 case 语句来判断是收入线还是支出线

select strftime('%Y-%m', date_col),
       sum(case when type = 'income' then amount else 0 end) income,
       sum(case when type = 'spending' then amount else 0 end) spending
  from test_table
 group by strftime('%Y-%m', date_col);

【讨论】:

  • 嗨@jarlh。我写这个答案时有一个“sqlite”标签
  • @jarth,这很奇怪。我已经更新了答案
  • 有人(不是 OP)弄乱了标签。我已经把 sqlite 标签放回去了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多