私はここにあなたの要件を理解していると思うし、私は実際にはかなり単純です。最初にYear
とCode
の組み合わせを取得する必要があります。TableA
とTableB
の両方にjoin
を入力して、条件付きsum
の計算を行うことで、最終結果のデータセットを作成することができます。私は私のアプローチのすべての機能を表示するには、いくつかの追加データを追加した
注:
-- Built test data
declare @a table([Year] int,[Month] int,Code int, Unit int, CA decimal(20,2));
declare @b table([Year] int,[Month] int,CodeP int, Unit_P int, CA_P decimal(20,0));
insert into @a values (2017,1,280,1,298259.42),(2017,1,281,0,0),(2017,2,280,1,298220.99),(2017,2,281,0,0),(2017,3,282,0,0),(2017,3,280,1,298033.09),(2017,4,280,1,298000.00);
insert into @b values (2017,1,280,1,250000),(2017,1,280,3,950000),(2017,3,281,1,250000),(2017,3,282,1,250000),(2017,6,282,1,250000);
-- Derived table to get all combinations of Year and Code across both tables
with y as
(
select [Year]
,Code
from @a
union -- Use of UNION ensures that a unique list is returned.
select [Year]
,CodeP
from @b
)
select y.[Year]
,y.Code
,sum(case when a.[Month] between 1 and 3 then a.Unit else 0 end) as Unit
,sum(case when a.[Month] between 1 and 3 then a.CA else 0 end) as CA
,sum(case when b.[Month] between 1 and 3 then b.Unit_P else 0 end) as Unit_P
,sum(case when b.[Month] between 1 and 3 then b.CA_P else 0 end) as CA_P
,isnull(sum(a.Unit),0) as Unit_PPP
,isnull(sum(a.CA),0) as CA_PPP
from y -- Then join this list onto both tables to get the totals
left join @a a
on(y.[Year] = a.[Year]
and y.Code = a.Code
)
left join @b b
on(y.[Year] = b.[Year]
and y.Code = b.CodeP
)
group by y.[Year]
,y.Code
order by y.[Year]
,y.Code;
出力:
+------+------+------+------------+--------+---------+----------+------------+
| Year | Code | Unit | CA | Unit_P | CA_P | Unit_PPP | CA_PPP |
+------+------+------+------------+--------+---------+----------+------------+
| 2017 | 280 | 6 | 1789027.00 | 16 | 4800000 | 8 | 2385027.00 |
| 2017 | 281 | 0 | 0.00 | 2 | 500000 | 0 | 0.00 |
| 2017 | 282 | 0 | 0.00 | 1 | 250000 | 0 | 0.00 |
+------+------+------+------------+--------+---------+----------+------------+
はUNION'、この場合には動作しない 'ですか? UNIONを使用して、TableNameを区別するために追加の列を追加することによって、ビューを作成できます。 – GauravKP
月はmoisと同じですか?両方のテーブルのすべての行を結合するには、すべて共用体が必要です。 –
はい moisを月として –