SQL aggregation came out different result

Hi Experts,


Query 1:
select
dt.[NAME],
d.[dealerid],
sum(ad.[WidgetInteraction]) as Pencils,
sum(ad.[WidgetLoad]) as Impressions,
isnull(dt.[SevenDayResponseAdj],0) as ResponseTime,
dt.[SFDC_Status],
sum (case when do.offertype= 1 then 1 else 0 end) as TotalLease,
sum (case when do.offertype=0 and d.vehiclestatus = 'New' then 1 else 0 end ) as NewTotalFinanceDeals,
Sum(case when dv.[ArchiveDealStatus]= 'CustomerSold' then 1 else 0 end) as 'Sold Archived'
from MakeMyDeal_com.[dbo].[adobe_data] ad
inner join [MMD_Feed].[dbo].[DART] dt on ad.dealerid=dt.dealerid
inner join mmd_feed..Deal d on d.DealerID=dt.dealerid
inner join mmd_feed..DealResponse doi on d.DealID=doi.dealid
inner join makemydeal_com..dealoffer do on doi.dealofferid=do.dealofferid
inner join mmd_feed..dealview dv on dv.dealid=d.dealid
inner join mmd_feed..dealer de on de.dealerid=d.dealerid
inner join mmd_feed.[dbo].[DealResponseMinAndMaxShopper] dms on dms.dealid=d.dealid and dms.FirstMessage=doi.DealResponseID
where
dt.name in (@DealershipName)  
and cast(ad.date as date)>=@StartDate and cast(ad.date as date)<=@EndDate
group by dt.[NAME],d.dealerid,isnull(dt.[SevenDayResponseAdj],0),dt.[SFDC_Status]

Query 2
select  
dt.[NAME],
dt.[dealerid],
sum(ad.[WidgetInteraction]) as Pencils,
sum(ad.[WidgetLoad]) as Impressions,
isnull(dt.[SevenDayResponseAdj],0) as ResponseTime,
dt.[SFDC_Status] as Status
into #dealeroverview
from MakeMyDeal_com.[dbo].[adobe_data] ad
join [MMD_Feed].[dbo].[DART] dt on ad.dealerid=dt.dealerid
where dt.name in (@DealershipName)
and cast(ad.date as date)>=@StartDate and cast(ad.date as date)<=@EndDate
group by dt.[NAME],dt.dealerid,isnull(dt.[SevenDayResponseAdj],0),dt.[SFDC_Status]


In fact, the numbers of pencils and impressions from query 2 are correct. So, I do not understand why the query 1 got a big number for pencils and impressions. And how can I modify the query 1? Thanks!
Query1query2
tanj1035Asked:
Who is Participating?
 
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
>I do not understand why the query 1 got a big number for pencils and impressions.
Offhand I see seven JOINs in query 1, so it is possible that you're seeing duplicate values because (1) the JOIN columns listed in the query are not all of the columns needed to guarantee a 1:1 join, or (2)  there are duplicate columns in some of these JOINed tables, causing duplicates in the 'base' table  adobe_data to display.
0
 
tanj1035Author Commented:
I agree with you. Probably, I will make query 1 to 2 datasets and join them after.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.