在这种情况下加入什么?

时间:2017-02-28 23:15:13

标签: sql postgresql

我在2017年的年度销售额中标记为Yearly,我们的所有时间广告资源标记为AllTime。我需要一个关于我可以使用什么连接的建议,或者我可以添加到我已经脚本的其他代码,这将使我在结果中显示标记为(null)的值。 (null)值表示来自Robin表的Yearly,但由于我在AllTime查询中没有该值,因此它在结果中显示为null。如果我将结果查询的顺序更改为from yearly left outer join alltime,则Red ArrowCaptain Marvel都会失去其尊重的位置,因为Yearly查询中的值都为零。如果我更改为from alltime left outer join yearly,则空值(Robin)消失。请分享您的建议。和往常一样,如果您需要其他详细信息,请告诉我们。

with AllTime as 

(select dp.Builder,
count(*) "My Inventory" from alldatainput dp
where Project_ID = 'GAP'
group by rollup ((dp.Builder))           

),

Yearly as 

(                   

select Builder,(count
(Sale_Date) filter (where extract(year from Sale_Date) = 2017 
and Project_ID = 'GAP'))
 - (count(Cancelled) filter (where extract(year from Cancelled) = 2017 
and Project_ID = 'GAP')) as "Net for 2017"
from allsalesdata sd
and Project_ID = 'GAP'
group by rollup((Builder))
having (count(Sale_Date) filter (where extract(year from Sale_Date) = 2017 
and Project_ID = 'GAP' ))
- (count(Cancelled) filter (where extract(year from Cancelled)   = 2017 and 
sd.Project_ID = 'GAP')) > 0
)

select alltime.Builder,coalesce(yearly."Net for 2017",0) 
as "YTD Home Sales", coalesce(alltime."My Inventory",0) as "My Inventory"
from allTime
full join yearly on allTime.Builder = yearly.Builder 
group by rollup((allTime.Builder,yearly."Net for 2017",alltime."My Inventory",
yearly.Builder))
order by yearly.Builder;   

结果:

  Builder           YTD Home Sales    My Inventory
  Batman                  3             86
  Superman                5             26
  Aquaman                 3             29
  Martian                 6             84
  Green Lantern           2             21
  Wonder Woman            1              3
  Flash                   2             74
  ****(null)              4              0   ************
  Cyborg                  2             54
  Batwing                 5             25
  Captain Marvel          0             15
  Red Arrow               0              1
                          33            0
                          0             418

1 个答案:

答案 0 :(得分:1)

select Builder, sum(x."YTD Home Sales") as "YTD Home Sales",
sum(x."My Inventory") as "My Inventory"
from (
select Builder, yearly."Net for 2017" as "YTD Home Sales",
0 as "My Inventory"
from yearly
UNION
select Builder, 0 as "YTD Home Sales",
alltime."My Inventory"
from alltime
) x 
group by Builder
order by Builder;