2016-10-20 11 views
0

レコードを数え、月ごとに数を表示する2つのテーブルがあります。SQL:テーブルの列を別のテーブルに追加

両方のカウントを同じテーブルに表示したいが、それらをどのように組み合わせるか分からない。

enter image description here

enter image description here

私はちょうどの右に、最初のテーブルに "IMカウント" 欄を追加したい "CRカウント。"

以下は、最初のテーブルのコードです。 2番目のテーブルは同様のコードですが、別のテーブルからデータを取得します。私の主な問題は、テーブル間で一致するカラムがないことです。 (年と月の列が技術的には一致しませんが、彼らは月額両方のカウントがあるという理由だけで。)

Use sm 

select 
year(planned_start) Year, 

Case 
    When month(planned_start) = 1 then 'January' 
    When month(planned_start) = 2 then 'February' 
    When month(planned_start) = 3 then 'March' 
    When month(planned_start) = 4 then 'April' 
    When month(planned_start) = 5 then 'May' 
    When month(planned_start) = 6 then 'June' 
    When month(planned_start) = 7 then 'July' 
    When month(planned_start) = 8 then 'August' 
    When month(planned_start) = 9 then 'September' 
    When month(planned_start) = 10 then 'October' 
    When month(planned_start) = 11 then 'November' 
    When month(planned_start) = 12 then 'December' 
end as Month, 
count(*) 'CR Count' 

from dbo.cm3rm1 
where planned_start between dateadd(Year,-1,getdate()) and getdate() 
and 
    category !='OAS Normal' 
group by year(planned_start), month(planned_start) 
order by year(planned_start), month(planned_start) 
+0

だけでなく、あなたが年を持っている場合と、あなたが参加することができます。しかし、他のデータをグループ化した後に参加すると、データが複製されます – Nemeros

+0

私はそれをどうやって行うのかは分かりません。私は一時的なテーブルのようなものが必要ですか?また、JOINを使用する場合は、どの列が一致するかを述べる必要がありますが、私の場合はYearとMonthの2つの列に一致する必要があります。私はそれをどうやって行うのか分からない。 –

+0

どのDBMSを使用していますか?あなたのクエリは無効な標準SQLです。 –

答えて

0

まあ、「アイデア」のため:

SELECT tmp_CR.Year, 
Case 
When tmp_CR.month = 1 then 'January' 
When tmp_CR.month = 2 then 'February' 
When tmp_CR.month = 3 then 'March' 
When tmp_CR.month = 4 then 'April' 
When tmp_CR.month = 5 then 'May' 
When tmp_CR.month = 6 then 'June' 
When tmp_CR.month = 7 then 'July' 
When tmp_CR.month = 8 then 'August' 
When tmp_CR.month = 9 then 'September' 
When tmp_CR.month = 10 then 'October' 
When tmp_CR.month = 11 then 'November' 
When tmp_CR.month = 12 then 'December' end as month, 
tmp_CR.CR_Count, 
tmp_IM.IM_Count 
FROM (
select 
    year(planned_start) Year, 
    month(planned_start) as Month, 
    count(*) as CR_Count 
from dbo.TABLE_1 
where planned_start between dateadd(Year,-1,getdate()) and getdate() 
    and 
    category !='OAS Normal' 
group by year(planned_start), month(planned_start) 
) tmp_CR 
INNER JOIN (
select 
    year(planned_start) Year, 
    month(planned_start) as Month, as Month, 
    count(*) as IM_Count 
from dbo.TABLE_2 
where planned_start between dateadd(Year,-1,getdate()) and getdate() 
    and 
    category !='OAS Normal' 
group by year(planned_start), month(planned_start) 
) tmp_IM ON tmp_CR.year = tmp_IM.year and tmp_CR.month = tmp_IM.month 
ORDER BY tmp_CR.Year, tmp_CR.month 
+0

もっと見やすくしたい場合は、2つのビューを作成し、単純な選択をしてください。..参加してください。 – Nemeros

+0

これは完璧で、素晴らしい仕事でした。本当にありがとう! –

+0

今問題が1つあります。 ORDER BYコマンドはJOINの後にあるため、数字ではなくアルファベット順にソートします。 –

関連する問題