伟大的SQL专家! :) 我的老板想要他的员工工作的月/年/日报告。我想到了我需要的大部分SQL查询,但最后一个是我的理解。
我有severas表:人员,服务,计划和提供的服务。表格计划包含每项服务的每个人的个人月计划。所以我需要一个查询返回服务的总价值,由特定服务的特定时间段内每个人提供的服务和同一服务中同一时期的计划工作量的汇总值。现在我有这样的事情:
SELECT SUM(BoRRenderedServices.ServiceCount),
BoREmployee.Name,
BoRServices.Service,
SUM(BoRTargets.Amount)
FROM BoRRenderedServices, BoREmployee, BoRServices, BoRTargets
WHERE (BoRTargets.EmployeeID = BoREmployee.ID)
AND (BoRTargets.ServiceID = BoRServices.ID)
AND (BoRRenderedServices.Date BETWEEN '2014-1-1' AND '2014-9-19')
AND (BoREmployee.DepartmentID = 'cc42cac9-5ac7-4614-9b7b-ef931a9a132b')
AND (BoRRenderedServices.EmployeeID = BoREmployee.ID)
AND (BoRRenderedServices.ServiceID = BoRServices.ID)
AND (BoRRenderedServices.ServiceID = '0fbf68bf-ace8-4ecb-ba07-7049046c0215')
GROUP BY BoREmployee.Name,
BoRServices.Service
但是这个查询是双重总和,它总结了两次提供的服务数量,同样适用于计划。我的意思是,每次它创建提供服务加工WHERE条件时 - 它也总结了计划,而不是仅将提供的服务添加到第一个sum语句中。
第1人,8月1日提供Service1三次,8月3日提供一次,7月4日提供4次。 8月份Person1的计划是3个,7月份计划是4个。
期望的输出:
--------------Plan Fact
Service1 1----------1
Service2 1----------2
Service3 1----------3
实际输出:
--------------Plan Fact
Service1 3----------3
Service2 3----------6
Service3 3----------9
答案 0 :(得分:1)
我更改了查询。 您可以创建视图或sql数据库。
with tbl1
as
(
SELECT
b.EmployeeId
,b.ServiceId
,c.Service
,d.Name
,Sum(b.Amount) Amount
FROM
BoRTargets b
inner join BoRServices c
on b.ServiceId = c.Id
inner join BoREmployee d
on b.EmployeeId = d.Id
WHERE (b.Date BETWEEN '2014-09-01' AND '2014-09-26')
AND (d.DepartmentID = 'cc42cac9-5ac7-4614-9b7b-ef931a9a132b')
GROUP BY b.EmployeeId, b.ServiceId, c.Service, d.Name
)
,
tbl2
as
(
SELECT
a.EmployeeId
,a.ServiceId
,c.Service
,d.Name
,SUM(a.ServiceCount) ServiceCount
FROM
BoRRenderedServices a
inner join BoRServices c
on a.ServiceId = c.Id
inner join BoREmployee d
on a.EmployeeId = d.Id
WHERE EXISTS(
SELECT 1
FROM BorTargets b
where (a.EmployeeId = b.EmployeeId and a.ServiceId = b.ServiceId)
AND (b.Date BETWEEN '2014-09-01' AND '2014-09-26'))
AND (d.DepartmentID = 'cc42cac9-5ac7-4614-9b7b-ef931a9a132b')
GROUP BY a.EmployeeId, a.ServiceId, c.Service, d.Name
)
select coalesce(a.Service, b.Service) Service, coalesce(a.Name, b.Name) Name, a.Amount, b.ServiceCount
from tbl1 a full join tbl2 b
on a.EmployeeId = b.EmployeeId
and a.ServiceId = b.ServiceId