我试图编写一个查询,总结2013日历年期间执行的所有程序,无论事件是发生在移动硬盘上还是发生在特定州内的固定网站上。
每个云端硬盘都是唯一的,可以在固定网站(CenterID)或移动网站上进行,这些网站与帐户(AccountID)相关联。我的查询如下:
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
但这些数字真的很高且不正确。所以我做的是删除其中一个连接(Account或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
如何修复原始查询,以基本上不会使预期值增加三倍的方式汇总这两列?
原始查询返回:
并分别使用帐户和中心运行查询:
答案 0 :(得分: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;