SQL - 加入多个Select语句

问题描述:

我想将四个不同的select语句组合成一个给我所需的输出。SQL - 加入多个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柱和息税前利润/销售收入列不同的看法。截至目前,我必须去excel,粘贴不同的值并安排它们,以便它们从开始日期(Date_Month Column中的第一个月)到结束日期(Date_Month Column中的上个月),然后移动不同的EBIT/Sales值在位。

第一份声明的数据来自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 

因此,他们是在同一个名单,但只要其中一列没有值时,它会发出空。

谢谢你的帮助。

P.s这些是数据中的估计值,所以不要与2012-01-31等中存在的2014值相混淆。

+0

所以,你只是想将四个结果集的行组合成一个结果集?你可以使用'union'或'union all'关键词吗? https://docs.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-union-transact-sql – user2023861

+0

你正在使用哪些DBMS? MySQL的? SQL Server?甲骨文? ... –

+0

此外,它看起来像你的查询之间唯一的区别是哪里的Y.Date_Year部分。如果是这样的话,只要做到这一点'在哪里Y.Date_Year在(2014,2015,...)' – user2023861

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

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; 
+0

好极了,这正是我想要的。我以前没有看到过“结束时的情况”,但效果很好。谢谢 –