如何 select 按日期列对数据进行分组? [ mysql ]

How to select grouped data by date column? [ mysql ]

我有 3 个表,usersuser_spentsuser_incomes

我想select 单个 用户的活动按日期分组和过滤。

Sql Fiddle Link 和 sql 到目前为止我已经尝试过: http://sqlfiddle.com/#!9/846c851/1

我做错了什么?你能给我一些建议吗?

我想要实现的示例数据:

name    spent   income  date
----------------------------------
Jack    8       12      2022-04-01
Jack    4       56      2022-04-02
Jack    NULL    44      2022-04-03
Jack    7       NULL    2022-04-04

示例数据。 (也包含在 sql fiddle 中)

Users Table:
id  name
1     Jack

User Spents:
id  user_id spent   date
1     1       2     2022-04-01
2     1       1     2022-04-01
3     1       5     2022-04-01
4     1       3     2022-04-02
5     1       1     2022-04-02

User Spents:
id  user_id income  date
1     1       44        2022-04-03
2     1       15        2022-04-02
3     1       41        2022-04-02
4     1       12        2022-04-01
5     2       54        2022-04-01

如有任何帮助,我们将不胜感激。谢谢。

可以使用UNION ALL获取user_spentsuser_incomes的所有行,然后加入users聚合:

SELECT u.id, u.name,
       SUM(t.spent) spent,
       SUM(t.income) income, 
       t.date
FROM users u
INNER JOIN (
  SELECT user_id, spent, null income, date FROM user_spents
  UNION ALL
  SELECT user_id, null, income, date FROM user_incomes
) t ON t.user_id = u.id
WHERE u.name = 'Jack' -- remove this condition to get results for all users
GROUP BY u.id, t.date;

参见demo