结合两个CTE块

时间:2020-01-08 18:18:15

标签: sql postgresql

有没有一种方法可以组合这两个cte块而不会丢失任何记录?我的目的是最大程度地减少此处发生的代码重复。我需要所有记录都显示在结果中,而不管它们是在cte1还是cte2中,还是两者都存在。

CTE 1-

with grouping (num, count) as 
(
SELECT num, count(*)
FROM pay t
where 
code = '1'
group by num
),
total (num, tot_count) as
(
select num, count(*)
from pay
group by num
)
select m.id, round(count/tot_count::decimal, 4), year
FROM total t
join grouping o
on t.num = o.num
join master m
on o.num = m.num;

CTE 2-

with grouping (num, count) as 
(
SELECT num, count(*)
FROM pay t
where 
code = '2'
group by num
),
total (num, tot_count) as
(
select num, count(*)
from pay
group by num
)
select m.id, round(count/tot_count::decimal, 4), year
FROM total t
join grouping o
on t.num = o.num
join master m
on o.num = m.num;

1 个答案:

答案 0 :(得分:0)

我没有要测试的样本数据,但似乎最大的不同在于您在WHERE CTE中的grouping语句中。

IN子句应该为您做到这一点:

with grouping (num, count) as 
(
SELECT num, count(*)
FROM pay t
where 
code IN ('1', '2')
group by num
),
total (num, tot_count) as
(
select num, count(*)
from pay
group by num
)
select m.id, round(count/tot_count::decimal, 4), year
FROM total t
join grouping o
on t.num = o.num
join master m
on o.num = m.num;

确认这是使用Sublime Text进行查询的唯一区别

enter image description here

相关问题