The results for each table must be calculated separately and then joined by date:
(每个表的结果必须分别计算,然后按日期合并:)
with
dates as (
select task_date from dpt1_taks union
select task_date from dpt2_taks union
select task_date from dpt3_taks
),
cte1 as (
select task_date,
coalesce(sum(assigned = 'x'), 0) dpt_assigned,
coalesce(sum(done = 'x'), 0) dpt_done
from dpt1_taks
group by task_date
),
cte2 as (
select task_date,
coalesce(sum(assigned = 'x'), 0) dpt_assigned,
coalesce(sum(done = 'x'), 0) dpt_done
from dpt2_taks
group by task_date
),
cte3 as (
select task_date,
coalesce(sum(assigned = 'x'), 0) dpt_assigned,
coalesce(sum(done = 'x'), 0) dpt_done
from dpt3_taks
group by task_date
)
select d.task_date,
c1.dpt_assigned dpt_assigned1, c1.dpt_done dpt_done1,
c2.dpt_assigned dpt_assigned2, c2.dpt_done dpt_done2,
c3.dpt_assigned dpt_assigned3, c3.dpt_done dpt_done3
from dates d
left join cte1 c1 on c1.task_date = d.task_date
left join cte2 c2 on c2.task_date = d.task_date
left join cte3 c3 on c3.task_date = d.task_date
See the demo .
(参见演示 。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…