2017-06-26 13 views
0

私は希望の出力を与えるものに4つの異なるselectステートメントを組み合わせようとしています。文のSQL - 複数のSelectステートメントを結合する

二彼らは私にDate_Month列およびEBIT /売上柱と異なるビューを与える

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 

(彼らと他の人がY.Date_Yearの例外と同一である)下記見ることができます。現在、私はExcelに行き、異なる値を貼り付けて、開始日(Date_Month列の最初の月)から終了日(Date_Month列の最後の月)に移動し、別のEBIT/Salesを移動するように配置する必要があります位置の値。

最初の声明には2012-01-31から2015-11-30までのデータがあり、2番目の声明には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

したがって、4つの結果セットの行を1つの結果セットに結合したいだけですか?あなたは 'union'または' union all'キーワードを使用できますか? https://docs.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-union-transact-sql – user2023861

+0

どのDBMSを使用していますか? MySQL? SQLサーバー?オラクル? ... –

+0

また、クエリの唯一の違いは 'where Y.Date_Year'部分のようです。もしそれが当てはまるならば、Y.Date_Year in(2014,2015、...)の ' – user2023861

答えて

1

条件付き集計またはピボットクエリを探しています。私は前者にもっと慣れていますので、ここにあります:

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

これは欲しいものでした。私は "Case、when、end"の構文を見たことはありませんでしたが、それは素晴らしい結果でした。ありがとうございました –

関連する問題