除了一个日期列之外,我还有两个几乎相同的MySQL表,我想将它们与一个选择查询合并,以创建一个显示两个日期的最终表。
如果在一个表中存在唯一的CCD_ 1;我想将另一个中的金额默认为0
。
下面是我的意思的一个例子:
Table1:
id | acc_id | 名称 | aug_amount||
---|---|---|---|---|
1 | 123 | 名称1 | 100 | |
2 | 456 | 名称2 | 200 | |
3 | 333 | 名称3 | 300 |
忽略PK列,这里有一个解决方案,我们将两个表合并,然后从中选择:
select acc_id, name, sum(aug_amount) as aug_amount, sum(sep_amount) as sep_amount
from (
select acc_id, name, aug_amount, 0 as sep_amount
from table1
union
select acc_id, name, 0, sep_amount
from table2
)z
group by acc_id, name
order by name;
acc_id | 名称 | aug_amount | >sep_amount|
---|---|---|---|
123 | 名称1 | 100 | 200 |
456 | 名称2 | 200 | 300 |
333 | 名称3 | 300 | 0 |
444 | 名称4 | 0 | 400 |