mysql - 表创建逻辑

标签 mysql sql

我希望获取两个表并执行数据转换来创建一个表。我有一个事件表用户表:

Events: {id, user_id, start_date, end_date, cost...}

Users: {id, name, ...}

我正在尝试创建一个表格,显示用户每天的支出,假设用户的起始成本为零,并且在每次事件后都会增加。

预期的输出将是:

{date, userid, beginning_balance, sum(cost), num_of_events}

我需要一些关于如何解决这个问题的指导,因为我不太熟悉 SQL 中的数据转换

最佳答案

您的要求有点不清楚,但您可能会追求这样的东西

drop table if exists event;
create table event(id int auto_increment primary key, user_id int,start_date date, end_date date, cost int);
insert into event (user_id,start_date , end_date, cost) values
(1,'2017-01-01','2017-01-01',10),(1,'2017-01-01','2017-01-01',10),
(1,'2017-02-01','2017-01-01',10),
(2,'2017-01-01','2017-01-01',10);

select e.user_id,start_date, 
            ifnull(
            (select  sum(cost)
            from event e1
            where e1.user_id = e.user_id and e1.start_date <e.start_date
            ),  0 )beginning_balance,
            sum(cost),count(*) 
           as num_of_events
from users u
join event e on e.user_id = u.userid
group by e.user_id,start_date

+---------+------------+-------------------+-----------+---------------+
| user_id | start_date | beginning_balance | sum(cost) | num_of_events |
+---------+------------+-------------------+-----------+---------------+
|       1 | 2017-01-01 |                 0 |        20 |             2 |
|       1 | 2017-02-01 |                20 |        10 |             1 |
|       2 | 2017-01-01 |                 0 |        10 |             1 |
+---------+------------+-------------------+-----------+---------------+
3 rows in set (0.03 sec)

关于mysql - 表创建逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47709737/

相关文章:

mysql - 如何在mysql中进行以下全文搜索?

php - Mysql从一个表中选择并插入到另一个表中

sql - PostgreSQL - 显示每个排序组的最后 N 行

php - 使用 MySQL 执行复杂的多表搜索查询

java - 在 Oracle 中设置时间戳

SQL 合并联合结果中的行并计算

mysql - 如何充分利用mysql中的索引?

mysql - 如何计算小时之间的总数 - MySQL

mysql - 我应该将大量数据放入另一个表以节省性能吗

具有不同列的两个表的 SQL 并集