2017-05-26 4 views
1

上ではないかもしれない:特定のための堆積CashDrawerテーブルショー総現金や小切手上のSQL Serverの2014 - 次のように私は2つのテーブルを持って参加したいが、レコードは1つのテーブルまたは他の

CashDrawer table 
+--------+---------------+-----------------+-----------+ 
| UserID | CashDeposited | ChecksDeposited | Timestamp | 
+--------+---------------+-----------------+-----------+ 
|  1 |    5 |    10 | 5/26/2017 | 
|  2 |    5 |    10 | 5/26/2017 | 
|  3 |    5 |    10 | 5/26/2017 | 
+--------+---------------+-----------------+-----------+ 

OtherPayments table 
+--------+---------------+-----------+ 
| UserID | OtherPayments | Timestamp | 
+--------+---------------+-----------+ 
|  4 |   15 | 5/26/2017 | 
|  4 |   15 | 5/26/2017 | 
|  4 |   15 | 5/26/2017 | 
+--------+---------------+-----------+ 

レコード日。 OtherPaymentsテーブルのレコードには、合計する必要のある個々の支払いが表示されます。

時々UserID 4は現金と小切手を受け取り、CashDrawerテーブルに表示されます。場合によっては、ユーザーID 1,2および3が他の支払いを受け入れ、OtherPaymentsTableにあることがあります。ユーザーIDとタイムスタンプのフィールドは、これら2つのテーブル間のキーですが、私はこの出力を取得するかどうかはわかりませんかそれも可能だ場合:

+--------+---------------+-----------------+---------------+-----------+ 
| UserID | CashDeposited | ChecksDeposited | OtherPayments | Timestamp | 
+--------+---------------+-----------------+---------------+-----------+ 
|  1 |    5 |    10 |    0 | 5/26/2017 | 
|  2 |    5 |    10 |    0 | 5/26/2017 | 
|  3 |    5 |    10 |    0 | 5/26/2017 | 
|  4 |    0 |    0 |   45 | 5/26/2017 | 
+--------+---------------+-----------------+---------------+-----------+ 
+1

「FULL OUTER JOIN」を実行します。 –

答えて

1

あなたは上の2つのUNION句は次のように選択し集約する必要があります。

select 
    UserID, 
    sum(CashDeposited), 
    sum(ChecksDeposited), 
    sum(OtherPayments), 
    Timestamp 
from 
(-- UNION needs the same number of columns in both Selects 
    select 
     UserID, 
     CashDeposited, 
     ChecksDeposited, 
     0 AS OtherPayments,-- doesn't exist in this table 
     Timestamp 
    from CashDrawer 

    union all 

    select 
     UserID, 
     0 AS CashDeposited, -- doesn't exist in this table 
     0 AS ChecksDeposited,-- doesn't exist in this table 
     OtherPayments, 
     Timestamp 
    from OtherPayments 
) as dt 
group by UserID, Timestamp 
+0

これは非常にエレガントなソリューションです - ありがとうございます。 – Jake

関連する問題