【问题标题】:Merge identical queries but with different conditions合并相同但条件不同的查询
【发布时间】:2019-12-26 08:58:38
【问题描述】:

我有 2 个这样的查询:

select count(id) filter (where data like '%"pmn":"CHILD_SEAT"%') as "Summ",
       count(id) filter (where data like '%"pmn":"CHILD_SEAT"%' and completed is true) as "Summ completed"
 from archived_order where created_user_login like 'exchangeAgent@shara' 
 and created between current_date - interval '1 month' and current_date;
select count(id) filter (where data like '%"pmi":2570%') as "Summ",
       count(id) filter (where data like '%"pmi":2570%' and completed is true) as "Sum completed"
 from archived_order where created_user_login not like 'exchangeAgent@shara' 
 and data like '%"cci":3%' 
 and created between current_date - interval '1 month' and current_date;

它们的区别在于数据条件。我需要将这 2 个查询作为一个输出彼此分开,并在其中添加更多查询,但具有不同的数据条件。

条件数据将从'%"pmi":2568%''%"cci":1%''%"pmi":2570%''%"cci":6%'

对于每个 pmi - cci 应该从 1 变为 6。

我试过 WITH 和 UNION 但不确定它是如何工作的,输出告诉我我不知道怎么做。

此查询将用于在 html 中创建报告,因此 count 应该可以写入 html 文件。

【问题讨论】:

  • 输出告诉我输出有什么问题? UNION 必须解决您的任务...
  • @Akina UNION 应该,但我做不到。所以我在寻求帮助。
  • 复制第一个查询文本,删除尾随;,添加用空格包裹的UNION ALL,添加第二个查询文本。就这样。我看到的唯一问题是如何区分每个单独的记录来自哪个子查询......
  • @Akina 这是主要问题之一,因为它将在报告中使用 - 所以应该以某种方式命名。
  • @Akina 我们可以做一个空列来声明什么是什么吗?

标签: postgresql


【解决方案1】:

也许你需要类似的东西

select count(id) filter (where data like '%"pmn":"CHILD_SEAT"%') as "Summ",
       count(id) filter (where data like '%"pmn":"CHILD_SEAT"%' and completed is true) as "Summ completed",
       'subquery-1' "what subquery is a source"
from archived_order 
where created_user_login like 'exchangeAgent@shara' 
  and created between current_date - interval '1 month' and current_date

UNION ALL

select count(id) filter (where data like '%"pmi":2570%'),
       count(id) filter (where data like '%"pmi":2570%' and completed is true),
       'subquery-2'
from archived_order 
where created_user_login not like 'exchangeAgent@shara' 
  and data like '%"cci":3%' 
  and created between current_date - interval '1 month' and current_date;

?

当然,识别文字可以是任何文字。包括数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2022-07-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多