将所有结果一并计算

时间:2019-12-26 10:28:41

标签: postgresql

我有UNION ALL的查询,看起来像这样,但随后进行了相同的查询,但有其他条件

select count(id) filter (where data like '%"pmn":"CHILD_SEAT"%') as "Summary",
       count(id) filter (where data like '%"pmn":"CHILD_SEAT"%' and completed is true) as "Summary Completed",
       'Child Seat' "Type of car-class/seat"
from archived_order 
where created_user_login like 'exchangeAgent@shara' 
  and created between current_date - interval '1 day' and current_date

UNION ALL

select count(id) filter (where data like '%"pmi":2568%'),
       count(id) filter (where data like '%"pmi":2568%' and completed is true),
       'Child seat economy 1-3'
from archived_order 
where created_user_login not like 'exchangeAgent@shara' 
  and data like '%"cci":4%' 
  and created between current_date - interval '1 day' and current_date

UNION ALL

select count(id) filter (where data like '%"pmi":2568%') as a,
       count(id) filter (where data like '%"pmi":2568%' and completed is true),
       'Child seat standart 1-3'
from archived_order 
where created_user_login not like 'exchangeAgent@shara' 
  and data like '%"cci":1%' 
  and created between current_date - interval '1 day' and current_date;

我尝试通过进行as进行计数,并尝试使用count选择它,但似乎不起作用。我不知道该如何计算2列count(id) filter (where data like '%"pmi":2568%')

这样的所有条目

以及所有类似count(id) filter (where data like '%"pmi":2568%' and completed is true)

的条目

我的目标是获得2个数字,该数字将是每个计数中所有值的总和。

 Summary | Summary Completed | Type of car-class/seat
---------+-------------------+-------------------------
   12899 |             10653 |
      97 |                94 | Child seat standart 1-3
      18 |                12 | Child seat economy 1-3

1 个答案:

答案 0 :(得分:1)

使用CTE可获得总和:

with cte as (
select count(id) filter (where data like '%"pmn":"CHILD_SEAT"%') as "Summary",
       count(id) filter (where data like '%"pmn":"CHILD_SEAT"%' and completed is true) as "Summary Completed",
       'Child Seat' "Type of car-class/seat"
from archived_order 
where created_user_login like 'exchangeAgent@shara' 
  and created between current_date - interval '1 day' and current_date

UNION ALL

select count(id) filter (where data like '%"pmi":2568%'),
       count(id) filter (where data like '%"pmi":2568%' and completed is true),
       'Child seat economy 1-3'
from archived_order 
where created_user_login not like 'exchangeAgent@shara' 
  and data like '%"cci":4%' 
  and created between current_date - interval '1 day' and current_date

UNION ALL

select count(id) filter (where data like '%"pmi":2568%') as a,
       count(id) filter (where data like '%"pmi":2568%' and completed is true),
       'Child seat standart 1-3'
from archived_order 
where created_user_login not like 'exchangeAgent@shara' 
  and data like '%"cci":1%' 
  and created between current_date - interval '1 day' and current_date
)
select sum("Summary") "Summary", sum("Summary Completed") "Summary Completed", null
from cte
union all
select * from cte