繁体   English   中英

SQL-连接多个Select语句

[英]SQL - join multiple Select statements

我正在尝试将四个不同的select语句组合成一个可以提供所需输出的语句。

可以在下面看到其中两个语句(除了Y.Date_Year外,其他两个都相同)

select sum(N.EBIT)/Sum(S.Sales), M.Date_Month from EBIT as N 
inner join Date_Year as Y on Y.Date_Year_Id = N.Date_Year_Id
inner join Sales As S on S.Company_Id = N.Company_Id
inner join Date_Month As M on M.Date_Month_Id=N.Date_Month_Id
where Y.Date_Year = 2014 and (N.Date_Month_Id = S.Date_Month_Id And N.Date_Year_Id = S.Date_Year_Id) and N.EBIT <> 0 and S.Sales <> 0
group by M.Date_Month

select sum(N.EBIT)/Sum(S.Sales), M.Date_Month from EBIT as N
inner join Date_Year as Y on Y.Date_Year_Id = N.Date_Year_Id
inner join Sales As S on S.Company_Id = N.Company_Id
inner join Date_Month As M on M.Date_Month_Id=N.Date_Month_Id
where Y.Date_Year = 2015 and (N.Date_Month_Id = S.Date_Month_Id And N.Date_Year_Id = S.Date_Year_Id) and N.EBIT <> 0 and S.Sales <> 0
group by M.Date_Month

通过Date_Month列和EBIT / Sales列,他们给了我不同的看法。 到目前为止,我必须精通Excel,将不同的值粘贴并排列它们,以便它们从开始日期(Date_Month列中的第一个月)到结束日期(Date_Month列中的最后一个月),然后将不同的EBIT /销售位置值。

第一个语句具有从2012-01-31到2015-11-30的数据,而第二个语句具有从2012-01-31到2016-11-30的数据。 我想要一个看起来像下面的表格:

Date_Month       EBIT/Sales 2014         EBIT/Sales 2015      
2012-01-31       0.09                     0.10
....             .....                    .....
2016-11-30       'Null'                   0.098

因此,它们在同一列表中,但是只要其中一列没有值,它将给出Null。

感谢您的任何帮助。

请注意,这些是数据中的估算值,因此请不要与2012-01-31等存在的2014年值混淆。

您正在寻找条件汇总或数据透视查询。 我更习惯前者,所以这里是:

select 
  m.date_month,
  sum(case when y.date_year = 2014 then n.ebit end) / 
   sum(case when y.date_year = 2014 then s.sales end) as "EBIT/Sales 2014",
  sum(case when y.date_year = 2015 then n.ebit end) / 
   sum(case when y.date_year = 2015 then s.sales end) as "EBIT/Sales 2015",
  sum(case when y.date_year = 2016 then n.ebit end) / 
   sum(case when y.date_year = 2016 then s.sales end) as "EBIT/Sales 2016",
  sum(case when y.date_year = 2017 then n.ebit end) / 
   sum(case when y.date_year = 2017 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
where y.date_year in (2014, 2015, 2016, 2017)
and n.ebit <> 0 
and s.sales <> 0
group by m.date_month;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM