用于在重复键

时间:2016-04-17 16:57:30

标签: sql sql-server

我有两张表debitTablecreditTable

debitTable有以下记录:

+----+-------+
| id | debit |
+----+-------+
| a  | 10000 |
| b  | 35000 |
+----+-------+

creditTable有以下记录:

+----+--------+
| id | credit |
+----+--------+
| b  | 5000   |
+----+--------+

SQL Server查询如何产生这些结果:

+----+----------------+--------------+
| id | debit | credit | debit-credit |
+----+----------------+--------------+
| a  | 10000 |   0    |     10000    |
| b  | 35000 |  5000  |     30000    |
+----+-------+--------+--------------+

3 个答案:

答案 0 :(得分:4)

您想使用select coalesce(d.id, c.id) as id, coalesce(credit, 0) as credit, (coalesce(debit, 0) - coalesce(credit, 0)) as DebitMinusCredit from (select id, sum(debit) as debit from debit group by id ) d full outer join (select id, sum(credit) as credit from debit group by id ) c on d.id = c.id; 。但是,在加入之前进行聚合非常重要:

full outer join

这使用{{1}}来确保包含两个表中的所有记录,即使id不在其中一个表中也是如此。加入前的聚合是为了避免在两个表中有多个行存在笛卡尔积时。

答案 1 :(得分:0)

您可以尝试“左连接”

Select * 
from debit d 
left join credit c on d.id = c.id

答案 2 :(得分:0)

select 
    debit.id, debit.debit, credit.credit, 
    debit.debit - credit.credit as [debit-credit]
from 
    debit 
left join 
    credit on debit.id = credit.id

但这仅基于借记卡:这意味着如果您的信用卡中的ID不是借记卡,则不会出现在此结果中。