我有两张桌子。一个是Cost_Table,另一个是Hire_Table。
Cost_Table 的布局如下所示:
sitename cost impressions deliverydate
Yahoo 100 10000 2016-01-01
Yahoo 200 20000 2016-01-02
Google 200 30000 2016-01-02
Google 500 50000 2016-01-03
Hire_Table 的布局如下所示:
site Hiredate
Yahoo 2016-03-01
Yahoo 2016-04-02
Yahoo 2016-04-28
Bing 2016-03-01
Bing 2014-06-01
我加入了两个表,我的代码列在下面:
select hire.site, cost.mediaspend,cost.impression,count(hire.site) as hires from Hire_Table Hire
Full Join
(select sitename, sum(cost) as mediaspend, sum(impressions) as impression from Cost_Table
where deliverydate between '2016-01-01' and '2016-07-31'
group by sitename) cost
on hire.site=cost.sitename
group by hire.site, cost.mediaspend,cost.impression
结果是:
sitename mediaspend impression hires
Yahoo 300 30000 3
Bing -- -- 2
但是,这不会给我网站名称,而不是 Hire_Table ,例如 Google 。我尝试使用 Coalesce ,但它也没有改变结果。的聚结(cost.sitename,hire.site)
我看到一些提到联盟功能的帖子。我认为它可能不适用于我的样本,因为我想从两个表中提取不同的内容。任何灯都将非常感激。谢谢!
答案 0 :(得分:0)
SELECT allSites.sitename, costs.mediaspend, costs.impressions, Hires.hires
FROM (SELECT sitename FROM Cost_Table
UNION
SELECT site FROM Hire_Table) as allSites
LEFT JOIN (SELECT sitename,
SUM(cost) as mediaspend,
SUM(impressions) as impressions
FROM Cost_Table
GROUP BY sitename) costs
ON allSites.sitename = costs.sitename
LEFT JOIN (SELECT site,
COUNT(Hiredate) as hires
FROM Hire_Table
GROUP BY site) Hires
ON allSites.sitename = Hires.site