sql - Table subsets comparison -


i using adventureworks database , sql server 2012 t-sql recipes book , got myself trouble on following example :

i have check salesquota in both 2007 , 2008 sales.salespersonquotahistory.

select sp.businessentityid , sum(s2008.salesquota) '2008' , sum(s2007.salesquota) '2007' sales.salesperson sp left outer join sales.salespersonquotahistory s2008   on sp.businessentityid = s2008.businessentityid     , year(s2008.quotadate) = 2008 left outer join sales.salespersonquotahistory s2007   on sp.businessentityid = s2007.businessentityid     , year(s2007.quotadate) = 2007 group sp.businessentityid 

first results are:

  businessentityid 2008                  2007 ---------------- --------------------- ---------------------   274              1084000.00            1088000.00   275              6872000.00            9432000.00   276              8072000.00            9364000.00   277              6644000.00            8700000.00 

just book says.

but try 2008 salesquota following query:

select sp.businessentityid,        sum(spqh.salesquota) '2008' sales.salesperson sp   left join sales.salespersonquotahistory spqh    on sp.businessentityid = spqh.businessentityid      , year(spqh.quotadate) = 2008  group sp.businessentityid 

and got this:

 businessentityid 2008 ---------------- ---------------------  274              271000.00  275              1718000.00  276              2018000.00  277              1661000.00 

what doing wrong here? think miss on left joins can't figure out what.

this 1 gives same result:

select businessentityid , sum(salesquota) '2008' sales.salespersonquotahistory year(quotadate) = 2008  group businessentityid    businessentityid 2008  ---------------- ---------------------  274              271000.00  275              1718000.00  276              2018000.00 

your first query creating cartesian product of results. instead, use conditional aggregation both values (which should match second query):

select sp.businessentityid,    sum(case when year(spqh.quotadate) = 2007 spqh.salesquota end) '2007',    sum(case when year(spqh.quotadate) = 2008 spqh.salesquota end) '2008' sales.salesperson sp   left join sales.salespersonquotahistory spqh       on sp.businessentityid = spqh.businessentityid group sp.businessentityid 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -