简体   繁体   English

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

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

I have 3 tables, users , user_spents , and user_incomes .我有 3 个表, usersuser_spentsuser_incomes

  • user_spents and user_incomes tables contains activities of users per date. user_spentsuser_incomes表包含每个日期的用户活动。
  • There can be multiple activities in one date per user.每个用户在一个日期内可以有多项活动。 (eg user can have multiple spent or income in 2022-04-01 date). (例如, user可以在 2022-04-01 日期有多个支出或收入)。
  • It's not mandatory that user must have spent or income in a given date用户必须在给定日期内spentincome不是强制性的

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_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;

See the demo .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM