【发布时间】:2017-07-13 14:03:43
【问题描述】:
我有一个代码可以为“移动”的宇宙产生所需的输出,在这个宇宙中它查看每个周期并给我信息。我想要另一个产生相同输出但选择不同的查询,a “当前”宇宙。
当前的 Universe 会像现在一样计算总和,但仅针对在数据库中最晚日期符合标准的公司。
目前,该代码为 Market_Cap 在 0 到 10000 2015 之间的公司生成 EBIT/Sales 2015,依此类推,但我更希望它为当前 Market_Cap 在 0 到 10000 之间的公司生成 EBIT/Sales 2015(最新 date_month在 Market_Cap 中)
我正在使用 Microsoft SQL Server Management Studio
我尝试在 sum(case when ... then) 语法中插入另一个标准,如“And c.company_id in(Select company_id from Market_cap where Market_Cap 介于 0 和 10000 之间且 Date = '2017-06-30 )) 但我得到错误:
无法对包含聚合或子查询的表达式执行聚合函数。
现在编码:
select m.date_month
,sum(case when y.date_year = 2015 AND c.Country_Id in (4,5,6) AND c.factSet_Level1_Id between 1 and 100 AND mm.Market_Cap between 0 and 10000 then n.EBIT end) / sum(case when y.date_year = 2015 AND c.Country_Id in (4,5,6) AND c.factSet_Level1_Id between 1 and 100 AND mm.Market_Cap between 0 and 10000 then s.Sales end) as 'EBIT/Sales 2015'
,sum(case when y.date_year = 2016 AND c.Country_Id in (4,5,6) AND c.factSet_Level1_Id between 1 and 100 AND mm.Market_Cap between 0 and 10000 then n.EBIT end) / sum(case when y.date_year = 2016 AND c.Country_Id in (4,5,6) AND c.factSet_Level1_Id between 1 and 100 AND mm.Market_Cap between 0 and 10000 then s.Sales end) as 'EBIT/Sales 2016'
,sum(case when y.date_year = 2017 AND c.Country_Id in (4,5,6) AND c.factSet_Level1_Id between 1 and 100 AND mm.Market_Cap between 0 and 10000 then n.EBIT end) / sum(case when y.date_year = 2017 AND c.Country_Id in (4,5,6) AND c.factSet_Level1_Id between 1 and 100 AND mm.Market_Cap between 0 and 10000 then s.Sales end) as 'EBIT/Sales 2017'
from EBIT as n
inner join Sales as s on s.company_id = n.company_id
and s.date_month_id = n.date_month_id
and s.date_year_id = n.date_year_id
inner join date_year as y on y.date_year_id = n.date_year_id
inner join date_month as m on m.date_month_id = n.date_month_id
inner join Market_Cap as mm on mm.Date_Month_Id = n.Date_Month_Id
and mm.Company_Id = n.Company_Id
inner join Company as c on c.Company_Id = n.Company_Id
where y.date_year between 2015 and 2017
and n.EBIT<> 0
and s.Sales<> 0
group by m.date_month;
正确的输出:
【问题讨论】:
标签: sum case-when multiple-conditions