我正在努力从早上开始做以下事情以获得解决方案。 我有2张桌子
表1和表2
Impressions Clicks RetailerId ManufacturerId Date
230 1273 5 104 2013-10-23 08:46:21.377
240 1220 12 104 2013-10-23 08:46:21.377
340 1530 8 102 2013-10-23 08:46:21.377
220 2012 25 102 2013-10-23 08:46:21.377
Earnings CreatedAt RetailerId ManufacturerId
20.0 2013-10-23 08:46:21.3775 25 104
21.0 2013-10-23 08:46:21.37712 12 104
15.5 2013-10-23 08:46:21.3778 12 102
16.2 2013-10-23 08:46:21.377 25 102
我需要加入这两个表,并且两个表都没有任何外键关系,因为table1数据被汇总然后更新。
我的意图是我需要为特定制造商和所选日期之间的所有零售商提取TotalClicks,Total Impressions,TotalEarnings。
当我做一些聚合函数时,我没有得到我期待的结果。
到目前为止,我所做的是
select rs.retailerid, rs.Clicks,asr.TotalValue, rs.ManufacturerId, asr.ManufacturerId
from(select rs.RetailerId,rs.ManufacturerId,SUM(rs.WidgetClicks) as Clicks
from RetailerStats rs group by RetailerId,ManufacturerId)rs
join
(select asr.retailerid,asr.ManufacturerId,SUM(asr.Earnings) as TotalValue
from AffiliateSchemeReports asr group by RetailerId,ManufacturerId)asr
on rs.RetailerId = asr.RetailerId
where rs.ManufacturerId = 104 and asr.ManufacturerId = 104
当我在聚合函数中给出datepart时,它没有给我实际值。
非常感谢任何帮助!
答案 0 :(得分:3)
一种想法是使用full outer join
来获取值,即使它们只在一个表中。我还将制造商ID移至join
条件:
select coalesce(rs.retailerid, asr.retailerid) as retailerid,
coalesce(rs.Clicks, 0) as clicks,
coalesce(asr.TotalValue, 0) as TotalValue,
rs.ManufacturerId, asr.ManufacturerId
from (select rs.RetailerId, rs.ManufacturerId, SUM(rs.WidgetClicks) as Clicks
from RetailerStats rs
group by RetailerId, ManufacturerId
) rs full outer join
(select asr.retailerid, asr.ManufacturerId, SUM(asr.Earnings) as TotalValue
from AffiliateSchemeReports asr
group by RetailerId, ManufacturerId
) asr
on rs.RetailerId = asr.RetailerId and
rs.ManufacturerId = asr.ManufacturerId
where (rs.ManufacturerId = 104 or asr.ManufacturerId = 104)