2014-11-21 59 views
0

我正在嘗試編寫一個查詢,以總結2013年日曆年中執行的所有過程,無論事件發生在移動驅動器上還是固定站點特定狀態。根據位置(狀態)查詢總數

每個驅動器都是唯一的,將發生在與帳戶(AccountID)關聯的固定站點(CenterID)或移動站點上。我的查詢是這樣的:

select sum(proceduresperformed), sum(productscollected) 
from DriveProjectionAndCollectedTotals DPaCT 
inner join rpt_DriveMaster DM on DPaCT.DriveID=DM.DriveID 
left outer join rpt_Accounts Acct on DM.AccountID=Acct.AccountID 
left outer join rpt_CenterDetail CD on DM.CenterID=CD.CenterID 
inner join rpt_AddressDetail AD on Acct.AccountID=AD.AccountID 
inner join rpt_AddressDetail AD2 on CD.CenterID=AD2.CenterID 
where AD.State='FL' 
or AD2.State='FL' 
and Year(DM.FromDateTime)=2013 

但是,這些數字真的很高,不正確。所以我所做的就是刪除連接(無論是賬戶或CenterDetail)之一,並運行查詢兩次拿到看起來更符合期望是什麼號碼:

select sum(proceduresperformed), sum(productscollected) 
from DriveProjectionAndCollectedTotals DPaCT 
inner join rpt_DriveMaster DM on DPaCT.DriveID=DM.DriveID 
left outer join rpt_Accounts Acct on DM.AccountID=Acct.AccountID 
--left outer join rpt_CenterDetail CD on DM.CenterID=CD.CenterID 
inner join rpt_AddressDetail AD on Acct.AccountID=AD.AccountID 
--inner join rpt_AddressDetail AD2 on CD.CenterID=AD2.CenterID 
where AD.State='FL' 
--or AD2.State='FL' 
and Year(DM.FromDateTime)=2013 

如何解決原查詢來總結這兩列的方式基本不會使期望值增加三倍?

原來的查詢返回:
Original Query Summary


並分別運行與賬戶和中心查詢:
Individual Summaries

+0

你似乎會沿着不同維度進行連接數據的一部分。結果在笛卡爾產品中。那是這個問題。如果沒有樣本數據和數據佈局,如何解決它是不可能的。 – 2014-11-21 17:10:06

+0

不確定您的意思,我可以提供哪些幫助? – MISNole 2014-11-21 17:25:31

回答

0

我回去,並使用UNION語句給我正確的答案:

select sum(procperf) as 'Procedures Performed' 
from (
select sum(proceduresperformed) as procperf 
from DriveProjectionAndCollectedTotals DPaCT 
inner join rpt_DriveMaster DM on DPaCT.DriveID=DM.DriveID 
left outer join rpt_Accounts Acct on DM.AccountID=Acct.AccountID 
inner join rpt_AddressDetail AD on Acct.AccountID=AD.AccountID 
where AD.State='FL' 
and Year(DM.FromDateTime)=2013 
UNION 
select sum(proceduresperformed) as procperf 
from DriveProjectionAndCollectedTotals DPaCT 
inner join rpt_DriveMaster DM on DPaCT.DriveID=DM.DriveID 
left outer join rpt_CenterDetail CD on DM.CenterID=CD.CenterID 
inner join rpt_AddressDetail AD2 on CD.CenterID=AD2.CenterID 
where AD2.State='FL' 
and Year(DM.FromDateTime)=2013 
) as a; 
+0

你應該使用'union all'。 – 2014-11-21 22:44:30

+0

我可以問爲什麼Union All應該用在Union上? – MISNole 2014-11-24 15:06:30

+0

'UNION'增加了刪除重複項的額外步驟。這充其量是浪費。在這種情況下,如果它們具有相同的值,它可以刪除其中的一行。 – 2014-11-24 21:44:52