我试图在employee_name和薪水的表上找到累计值,这是10年的数据.....所以我怎样才能找到每个人的累计金额....而不仅仅是添加所有员工。 .....
例如:
EMPLOYEE SALARY
JAMES 100
JAMES 100
JAMES 100
SAM 100
SAM 100
SAM 400
这是我的表:
我试图将其设为:
EMPLOYEE SALARY CUMULATIVE_SUM
JAMES 100 100
JAMES 100 200
JAMES 100 300
SAM 100 100
SAM 100 200
SAM 400 600
我怎样才能得到这样的结果?
答案 0 :(得分:1)
如果您添加工资日期,可以这样做。请看下表:
mysql> select * from salaries;
+-------+-------------+--------+
| name | salary_date | amount |
+-------+-------------+--------+
| james | 2014-01-01 | 100.00 |
| james | 2014-02-01 | 100.00 |
| james | 2014-03-01 | 100.00 |
| sam | 2014-01-01 | 400.00 |
| sam | 2014-02-01 | 400.00 |
| sam | 2014-03-01 | 400.00 |
+-------+-------------+--------+
6 rows in set (0.00 sec)
进行以下查询:
select e1.name, e1.salary_date, e1.amount,
(select sum(e2.amount)
from salaries e2
where e2.name = e1.name and e2.salary_date <= e1.salary_date) as cumulated
from salaries e1;
结果是:
+-------+-------------+--------+-----------+
| name | salary_date | amount | cumulated |
+-------+-------------+--------+-----------+
| james | 2014-01-01 | 100.00 | 100.00 |
| james | 2014-02-01 | 100.00 | 200.00 |
| james | 2014-03-01 | 100.00 | 300.00 |
| sam | 2014-01-01 | 400.00 | 400.00 |
| sam | 2014-02-01 | 400.00 | 800.00 |
| sam | 2014-03-01 | 400.00 | 1200.00 |
+-------+-------------+--------+-----------+
使用mysql测试。祝你好运: - )
答案 1 :(得分:0)
您需要使用GROUP BY
按人分组,然后您可以使用AVG
等聚合函数。这只会给你每人一笔钱(不是中间值,如你的例子)。
mysql> CREATE TABLE people(id int, salary int);
mysql> INSERT INTO people VALUES (1, 1), (1, 10), (1, 100),
(2, 2), (2, 20), (2, 200);
mysql> SELECT id, SUM(salary), AVG(salary) FROM people GROUP BY id;
+------+-------------+-------------+
| id | sum(salary) | avg(salary) |
+------+-------------+-------------+
| 1 | 111 | 37.0000 |
| 2 | 222 | 74.0000 |
+------+-------------+-------------+
2 rows in set (0.00 sec)