简体   繁体   English

DB2 SQL使用group by读取2个表

[英]DB2 SQL reading 2 tables using group by

I need to read 2 tables selecting unique dates and count the number of entries from both tables by date. 我需要阅读2个选择唯一日期的表格,并按日期对两个表格中的条目数进行计数。

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

The final result set should be: 最终结果集应为:

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

could someone help how should I write the code with final result as above 有人可以帮助我如何编写最终结果如上所述的代码

I would recommend doing this using union all and group by : 我建议使用union allgroup 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;

Do union all from table1 and table2 then do a group by. 从表1和表2合并所有,然后进行分组。 Sum up the row count per table source. 总结每个表源的行数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM