2017-10-27 7 views
1

2つのテーブルからすべてのレコードを取得し、1日ごとにグループ化された金額の合計を計算したいが、日付一致は両方の値を示します。たとえば は私が持っている:どのようにすべてのレコードを選択することができ、両方のテーブルの一致が1つのレコードに含まれます

table 1 In 
id  ammount   date 
1   300    2017-10-25 
2   150    2017-10-25 
3   550    2017-10-27 


table 2 out 
1   250    2017-10-27 
2   410    2017-10-28 
3   830    2017-10-29 

と、私はこの結果たい:

result 
ammount in   ammount out  date 
450     0     2017-10-25 
550     250    2017-10-27 
0     410    2017-10-28 
0     830    2017-10-29 

任意のアイデアはどのようにこれを作るためには?

+1

ですあなたは使っていますか?オラクル? SQLサーバー? PostgreSQL? MySQL? ...あなたが答えるDBMSでSQL質問に常にタグを付けます。 –

答えて

1

これはSQLite3ので動作します:完全外部2つの集計テーブルに参加しています

create table t1(id,amount,date); 
insert into t1 values 
(1,300,'2017-10-25'), 
(2,150,'2017-10-25'), 
(3,550,'2017-10-27'); 

create table t2(id,amount,date); 
insert into t2 values 
(1,250,'2017-10-27'), 
(2,410,'2017-10-28'), 
(3,830,'2017-10-29'); 

select sum(amount_in) as amount_in, sum(amount_out) as amount_out, date 
from (
    select amount as amount_in, 0 as amount_out, date from t1 
    union all 
    select 0 as amount_in, amount as amount_out, date from t2 
) 
group by date; 
+1

良いアイデア。しかし、これは 'UNION ALL'でなければなりません。それ以外の場合は、同じ日に同量の行を不注意に削除します。 –

+0

そうです!修正されました。 – tonypdmtr

+0

ええ、それは動作します、ちょうどメインの選択にエイリアスを取得する必要がありますし、うまく動作します。 –

0

select 
    coalesce(tin.ammount, 0) as ammount_in, 
    coalesce(tout.ammount, 0) as ammount_out, 
    date 
from   (select date, sum(ammount) as total from table_in group by date) tin 
full outer join (select date, sum(ammount) as total from table_out group by date) tout 
    using (date); 
0

これは何DBMS MS SQLサーバで動作

SELECT  SUM(amount_in) AS amount_in, SUM(amount_out) AS amount_out, date1 
FROM   (SELECT  amount AS amount_in, 0 AS amount_out, date1 
        FROM   t1 
        UNION ALL 
        SELECT  0 AS amount_in, amount AS amount_out, date1 
        FROM   t2) AS derivedtbl_1 
GROUP BY date1 
関連する問題