我需要阅读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
有人可以帮助我如何用最终结果编写代码
答案 0 :(得分:0)
我建议您使用union all
和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;
答案 1 :(得分: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