有点正确的加入

sort of right join

我有以下两个 SQL table(在 sql 服务器中):

Payment(physical payment made)
+----+-------+-----------+---------------------+
| id |Amount | BookingId | Transaction Type    |
+----+-------+-----------+---------------------+
| 1  | 10000 |   2       |   p(normal payment) |
+----+-------+-----------+---------------------+
| 2  | 90000 |   2       |   p(normal payment) |
+----+-------+-----------+---------------------+
| 3  | 8000  |   2       |   p(normal payment) |
+----+-------+-----------+---------------------+
| 4  | 8000  |   3       |   r(refunds)        |
+----+-------+-----------+---------------------+
| 5  | 10000|    4       |   r(refunds)        |
+----+-------+-----------+---------------------+

退款(将在未来进行)

+----+--------+-----------+
| id | Amount | BookingId |
+----+--------+-----------+
| 1  | 10000  |   2       |
+----+--------+-----------+

第一个 table 包含不同的付款类型,正常付款、退款、实际根据预订 ID 进行的代币付款。

第二个 table 包含将为该特定预订 ID 进行的未来退款记录。

我正在领取第一个 table 的所有退款付款,但我还想在一个数据集中领取 bookingId 2。

结果

+----+-------+-----------+------------+
|id  |Amount | BookingId | Difference |
+----+-------+-----------+------------+
| 4  | 8000  |    3      |  0         |
+----+-------+-----------+------------+
| 5  | 10000 |    4      |  0         |
+----+-------+-----------+------------+
| 6  |   0   |    2      |  10000     |
+----+-------+-----------+------------+

如有任何帮助,我们将不胜感激。预订 3 和 4 有退款但 2 没有

使用UNION

SELECT id, Amount, BookingId, 0 AS Difference FROM FIrstTable WHERE Transaction Type = 'R'
UNION ALL
SELECT id, 0 AS Amount, BookingId, Amount AS Difference FROM SecondTable