我希望采用两个表来执行数据转换以创建单个表。我有events table
和user table
:
Events: {id, user_id, start_date, end_date, cost...}
Users: {id, name, ...}
我正在尝试创建一个表格,显示用户在每日级别上花费,假设用户的起始成本为零,并且在每次事件后都会上升。
预期的输出将是:
{date, userid, beginning_balance, sum(cost), num_of_events}
我需要一些指导如何解决这个问题,因为我不熟悉SQL中的数据转换
答案 0 :(得分:0)
您可以尝试此查询
SELECT
data,
User.id AS userid,
0 AS beginning_balance,
SUM(cost) AS cost,
COUNT(0) AS num_of_events
FROM
Users
LEFT JOIN Events ON (user_id = Users.id)
GROUP BY
Users.id
答案 1 :(得分:0)
您的要求有点不清楚,但您可能会遇到类似的事情
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)