2014-09-19 67 views
0

偉大的sql專家! :) 我的老闆希望每月/每年/每天的員工工作報告。我想到了大部分我需要的SQL查詢,但最後一個超出了我的理解範圍。SQL多語言查詢與兩個sum語句

我有幾個表格:人員,服務,計劃和ProvidedServices。表格計劃包含每個服務上每個人的個人月計劃。所以我需要一個查詢,它返回每個人在特定服務的特定時間段提供的服務的總價值以及同一服務上同一時期計劃工作量的彙總值。現在我有這樣的事情:

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日3次提供服務1次,8月3日1次,7月4日4次。 Person1八月份的計劃是三次,七月份是四次。

所需的輸出:
--------------Plan Fact Service1 1----------1 Service2 1----------2 Service3 1----------3
實際輸出:
--------------Plan Fact Service1 3----------3 Service2 3----------6 Service3 3----------9

+1

你能後的實際數據和期望的輸出?你有什麼樣的DB,MySQL,SQL-Server,Oracle,什麼版本?您還可以在[sqlfiddle](http://sqlfiddle.com/)上發佈示例 – Max 2014-09-19 08:05:29

+1

舊學校JOIN已經破舊大約20年了,請使用JOIN關鍵字。 – HoneyBadger 2014-09-19 08:16:33

+0

在sqlfiddle.com上提供一個示例 – Max 2014-09-26 10:14:32

回答

1

我更改查詢。 你可以創建視圖或你的sql數據庫。

檢查SqlFiddle

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 
+0

如果沒有問題,請將其標記爲答案 – Max 2014-09-29 13:48:58

+0

不可以,同樣的結果是,如果我添加了一些更多的呈現服務。看http://sqlfiddle.com/#!3/72bce/1,它仍然雙倍總結Amount列。 – 2014-09-30 10:32:07

+0

我在表A中添加了三行。 – 2014-09-30 10:34:17