1

我需要阅读 2 个选择唯一日期的表,并按日期计算两个表中的条目数。

Example:
table 1                table 2
date                   date
----------             --------
2018-03-20             2018-03-15
2018-03-20             2018-03-20
2018-03-25             

最终结果集应该是:

date         sum from table 1  sum from table 2    total count
2018-03-15    0                     1                      1
2018-03-20    2                     1                      3
2018-03-25    1                     0                      1

有人可以帮助我如何编写最终结果如上的代码

4

2 回答 2

0

将 table1 和 table2 中的所有内容联合起来,然后进行分组。总结每个表源的行数。

select date,
   sum(case when tbl=1 then 1 else 0 end) as sum_tbl_1,
   sum(case when tbl=2 then 1 else 0 end) as sum_tbl_2,
   sum(1) as total_count
from (
  select date, 1 as tbl
  from myTable1
    union all
  select date, 2 as tbl
from myTable2) t
group by t.date
order by t.date
于 2018-04-16T23:46:10.163 回答
0

我建议使用union alland执行此操作group by

select date, sum(in_1) as sum_1, sum(in_2) as cnt_2,
       sum(in_1) + sum(in_2) as total_cnt
from ((select date, 1 as in_1, 0 as in_2 from table1) union all
      (select date, 0, 1 from table2)
     ) t
group by date
order by date;
于 2018-04-16T23:41:07.363 回答