如何按日期列选择分组数据? [ mysql ]
我有 3 个表:users
、user_spents
和 user_venues
。
user_spents
和user_venues
表包含用户每个日期的活动。- 每个用户在一个日期内可以进行多项活动。 (例如,
用户
可以在 2022 年 4 月 1 日有多次支出或收入)。 - 不强制要求用户在给定日期内必须有
支出
或收入
我想选择单个用户的活动按日期分组和过滤。
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
任何帮助将不胜感激。谢谢。
I have 3 tables, users
, user_spents
, and user_incomes
.
user_spents
anduser_incomes
tables contains activities of users per date.- There can be multiple activities in one date per user. (e.g.
user
can have multiple spent or income in 2022-04-01 date). - It's not mandatory that user must have
spent
orincome
in a given date
I want to select activities of single user grouped and filtered by date.
Sql Fiddle Link and sql What I have tried so far: 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)
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
UNION ALL
获取user_spents
和user_venues
的所有行,然后加入users
进行聚合:请参阅演示。
You can use
UNION ALL
to get all the rows ofuser_spents
anduser_incomes
and then join tousers
to aggregate:See the demo.