如何选择所有记录,并且两个表的匹配都在一条记录中

时间:2017-10-27 20:32:56

标签: sql join

我希望从两个表中获取所有记录,计算按天分组的金额总和,但是当日期匹配显示两个值时,显示两者的所有记录。 例如,我有:

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

任何想法如何制作这个?

3 个答案:

答案 0 :(得分:1)

这适用于SQLite3:

dfs = [ddict[x] for x in frames_to_concat['Sheets']]
sufs = [suff[x] for x in suffs['Suffixes']]

df4 = pd.concat([x.add_suffix(sep0 + y) 
          for x, y in zip(dfs, sufs)], axis=1, join='outer')

答案 1 :(得分: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);

答案 2 :(得分:0)

这适用于MS sql server

    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