i wana在mysql中使用between date和sum of balance column not between dates,group by customer\ id获取余额列数据的总和

vcirk6k6  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(388)

这是我的mysql表,

  1. customer_id balance date
  2. 1 300 1-1-2018
  3. 2 200 3-1-2018
  4. 1 100 5-1-2018
  5. 2 50 5-1-2018
  6. 1 30 6-1-2018
  7. 1 10 7-1-2018
  8. 4 50 7-1-2018

我想要这个结果,如果我选择从日期1到5

  1. customer_id current previous total
  2. 1 400 40 440
  3. 2 250 0 250
  4. 3 0 50 50
z9zf31ra

z9zf31ra1#

  1. select id
  2. , sum(a.balance) as current
  3. , sum(b.balance) as previous
  4. , sum(a.balance) + sum(b.balance) as total
  5. from mytable as a
  6. join mytable as b on a.id = b.id
  7. where a.date between date('2018-01-01') and date('2018-05-01')
  8. and b.date < date('2018-01-01')
  9. group by id;

请注意,您可能希望根据变量确定日期范围。

kq4fsx7k

kq4fsx7k2#

一种方法是使用一对计算聚合值的子查询。因此,可以使用子等式选择指定日期范围内的和以及该范围外的和。然后添加 coalesce 替换 null 有效金额(0)。

  1. select
  2. customer_id,
  3. coalesce(current, 0),
  4. coalesce(previous, 0),
  5. coalesce(current, 0) + coalesce(previous, 0) total
  6. from
  7. (
  8. select
  9. customer_id,
  10. (
  11. select sum(balance)
  12. from balance b
  13. where b.customer_id = a.customer_id
  14. and b.date between '2018-01-01' and '2018-05-01'
  15. group by b.customer_id
  16. ) current,
  17. (
  18. select sum(balance)
  19. from balance c
  20. where c.customer_id = a.customer_id
  21. and c.date not between '2018-01-01' and '2018-05-01'
  22. group by c.customer_id
  23. ) previous
  24. from balance a
  25. ) c
展开查看全部

相关问题