[英]How to select grouped data by date column? [ mysql ]
I have 3 tables, users
, user_spents
, and user_incomes
.我有 3 个表,
users
、 user_spents
和user_incomes
。
user_spents
and user_incomes
tables contains activities of users per date. user_spents
和user_incomes
表包含每个日期的用户活动。user
can have multiple spent or income in 2022-04-01 date). user
可以在 2022-04-01 日期有多个支出或收入)。spent
or income
in a given datespent
或income
不是强制性的I want to select activities of single user grouped and filtered by date.我想按日期对单个用户的 select 活动进行分组和过滤。
Sql Fiddle Link and sql What I have tried so far: http://sqlfiddle.com/#!9/846c851/1 Sql Fiddle Link 和 sql 到目前为止我尝试了什么: http://sqlfiddle.com/#!9/846c851/1
What am I doing wrong?我究竟做错了什么? Can you give me any suggestions?
你能给我什么建议吗?
Example data what I want to achieve:我想要实现的示例数据:
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
Sample data.样本数据。 (Alse included in sql fiddle)
(也包含在 sql 小提琴中)
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
Any help will be appreciated.任何帮助将不胜感激。 Thanks.
谢谢。
You can use UNION ALL
to get all the rows of user_spents
and user_incomes
and then join to users
to aggregate:您可以使用
UNION ALL
获取user_spents
和user_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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.