查询使用其他计算列计算列

时间:2017-11-17 12:04:33

标签: sql sql-server reporting-services

表:项目详情

+-----+------------------+------------+--------------+------------+
| GPN | EmployeePosition | Project.No | ChargedHours | PayPerHour |
+-----+------------------+------------+--------------+------------+
|   2 | B                |        101 |           50 |         57 |
|   3 | C                |        100 |           75 |         44 |
|   4 | D                |        100 |          100 |      24.75 |
|   5 | E                |        103 |          125 |      19.25 |
|   6 | F                |        101 |          150 |         16 |
|   7 | C                |        100 |          175 |         44 |
+-----+------------------+------------+--------------+------------+

我需要找出每个项目的总薪酬。首先,我必须找出每位员工的总薪酬,并将其分组为 Project.No

下表显示使用其他2个现有列创建的每位员工的总薪酬

+-----+-------------+---------+------------+----------+----------------+
| GPN | EmpPosition | Proj.No | ChargedHrs | PayPerHr | TotalPayPerEmp |
+-----+-------------+---------+------------+----------+----------------+
|   2 | B           |     101 |         50 |       57 |         993.75 |
|   3 | C           |     100 |         75 |       44 |           2850 |
|   4 | D           |     100 |        100 |    24.75 |           3300 |     
|   5 | E           |     103 |        125 |    19.25 |        2406.25 |
|   6 | F           |     101 |        150 |       16 |           2400 |    
|   7 | C           |     100 |        175 |       44 |           7700 |
+-----+-------------+---------+------------+----------+----------------+

我的查询:

 Select EngNumber, SUM([CharHrs])[SumOfChargedHours], Levell, CostPH, 
SUM([CharHrs])*CostPH [TotalPayPerEmployee]
FROM data1.dbo.PayedPerHour
GROUP BY EngNumber, Levell, TotalPayPerEmployee, CostPH
ORDER BY EngNumber;

Update data1.dbo.PayedPerHour
SET CostPH = CASE Levell 
                      WHEN 'Associate Director' THEN '79.75' 
                      WHEN 'Senior Manager' THEN '57' 
                      WHEN 'Manager' THEN '44'
                      WHEN 'Senior' THEN '24.75'
                      WHEN 'Staff 2, 3 & 4' THEN '19.25'
                      WHEN 'Staff 1' THEN '16'
                      ELSE 'NULL'
                      END
 WHERE Levell IN('Associate Director', 'Senior Manager','Manager', 'Senior', 
'Staff 2, 3 & 4', 'Staff 1');

我想通过 Proj.No TotalPayPerEmp 进行分组,但我无法完成它。 我会在查询中犯下愚蠢的错误,因为我对sql很新,所以请后悔

预期表格:

+---------+--------------------+
| Proj.No | TotalPayPerProject |
+---------+--------------------+
|     100 |           14093.75 |
|     101 |               5250 |
|     103 |            4881.25 |
+---------+--------------------+

1 个答案:

答案 0 :(得分:1)

我认为这可以使用你的一些算法来完成,除了ProjectNo粒度:

SELECT ProjectNo
      ,SUM(ChargedHours*PayPerHour) [TotalPayPerProject]
FROM ProjectDetails
GROUP BY ProjectNo  

这给出了输出:

ProjectNo   TotalPayPerProject
100         13475
101         5250
103         2406.25

由于某种原因,这与您的预期输出不同。

这是一个SQL小提琴:http://sqlfiddle.com/#!6/21a33/2/0