连接和别名表中的问题

时间:2018-04-23 20:11:17

标签: mysql sql

我正在尝试解决一个问题,即来自特定部门的每个工作人员销售产品并使其获利1000。我想知道每个月公司的利润或亏损。假设唯一的利润来自销售,成本是所有工人的工资。

Table dept_worker
+-----------+---------+------------+------------+
| worker_id | dept_n  | from_date  | to_date    |
+-----------+---------+------------+------------+
|  10002    |  25     | 1996-08-03 | 9999-01-01 |
|  10016    |  25     | 1998-02-11 | 9999-01-01 |
|  10034    |  25     | 1995-04-12 | 1999-10-31 |
+-----------+---------+------------+------------+

Table salaries
+----------+--------+------------+------------+
| worker_id| salary | from_date  | to_date    |
+----------+--------+------------+------------+
|  10001   |  617   | 1986-04-26 | 1987-06-26 |
|  10002   |  600   | 1996-08-03 | 9999-01-01 |
|  10016   |  602   | 1998-02-11 | 9999-01-01 |
|  10034   |  674   | 1995-04-12 | 1999-10-31 |
|  10100   |  900   | 2000-07-25 | 2002-06-25 |
+----------+--------+------------+------------+

我尝试了两种不同的方法。我尝试使用WHERE dept_n = '25'但结果不是预期的,因为我正在过滤所有内容。

    SELECT MONTH(from_date) AS 'Months', COUNT(worker_id)*1000 AS 'Profit', 
    SUM (salary) AS 'Costs', (COUNT(worker_id)*1000-SUM(salary)) AS 'Diff'
    FROM dept_worker JOIN salaries using(from_date,worker_id)
    GROUP BY Month
    ORDER BY Diff DESC;

第二个(此查询不会给我任何结果):

    SELECT MONTH(from_date) AS 'Months', 
    (SELECT COUNT(worker_id)*1000 FROM dept_worker WHERE dept_n = '25') AS 'Profits', SUM(salary) 
    FROM dept_worker JOIN salaries using(from_date)
    GROUP BY Months;

预期结果:

+----------+--------+------------+-------------------+
| Months   | Profits| Costs      | Profits - Costs   |
+----------+--------+------------+-------------------+
|  1       | 4456   |14478       |-10022             |
|  2       | 4105   |14824       |-10719             |
|  3       | 4379   |16130       |-11751             |
|  4       | 4329   |15562       |-11233             |
| (...)    | (...)  |(...)       |(...)              |         
+----------+--------+------------+-------------------+

1 个答案:

答案 0 :(得分:0)

尝试从此开始:

   SELECT MONTH(from_date) AS 'Months', COUNT(worker_id) over(partition by dept_n order by dept_n) * 1000 AS 'Profit', 
    SUM (salary) over(partition by dept_n order by dept_n) AS 'Costs' 
    FROM dept_worker JOIN salaries using(from_date,worker_id)
    GROUP BY  MONTH(from_date)