我正在试图找出最佳方法来获得一个人在一个项目名称上花费的时间总和遵循某种模式
+--------------------+----------------+-----------------+
| Tbl_Employee | Tbl Projects | tbl_timesheet |
+--------------------+----------------+-----------------+
| employee_id | project_id | timesheet_id |
| employee_full_name | cws_project_id | employee_id |
| | | project_id |
| | | timesheet_hours |
+--------------------+----------------+-----------------+
这是我到目前为止的查询
select
te.employee_id,
te.employee_last_name,
te.employee_first_name,
te.employee_department,
te.employee_type_id,
te.timesheet_routing,
sum(tt.timesheet_hours) as total_hours,
month(tt.timesheet_date) as "month",
year(tt.timesheet_date) as "year"
from tbl_employee te
left join tbl_timesheet tt
on te.employee_id = tt.employee_id
join tbl_projects tp
on tp.project_id = tt.project_id
where te.employee_active = 1
and te.employee_id > 0
and employee_department IN ("Project Management","Engineering","Deployment Srvs.")
and year(tt.timesheet_date) = 2015
group by te.employee_last_name, year(tt.timesheet_date), month(tt.timesheet_date)
order by employee_last_name
我需要添加到我的select语句中的是
的效果sum(tt.timesheet_hours) as where cws_project_id like '%Training%' as training
简而言之,我需要知道员工为cws_project_id
包含单词 Training 的项目贡献的小时数。我知道你不能在一个Sum中添加where子句但我似乎无法找到另一种方法来实现它。
如果这有所不同,我需要多次这样做 - 即project_name包含不同的单词。
非常感谢您提供的任何帮助。我希望这不清楚是泥。
答案 0 :(得分:1)
以下是您要寻找的一般形式:
SELECT SUM(IF(x LIKE '%y%', z, 0)) AS ySum
更一般的
SELECT SUM(IF([condition on row], [value or calculation from row], 0)) AS [partialSum]
编辑:有关更多RDBMS可移植性(早期版本的MS SQL不支持此形式的IF
):
SELECT SUM(CASE WHEN [condition on row] THEN [value or calculation from row] ELSE 0 END) AS [partialSum]