简体   繁体   English

PostgreSQL在单个查询中运行具有不同列的多个选择语句

[英]postgresql run multiple select statements with different columns in single query

I have 14 queries, such as 我有14个查询,例如

select activities.type, sum(activity_fees.amount) 
from activity_fees inner join activities 
on activity_fees.activity_id = activities.id 
where DATE(activities.due_at) = current_date - INTERVAL '1 day' 
group by activities.type

SELECT avg(activities.rating) 
FROM fellows 
inner join auth on a.a_id = f.id 
inner join activities on activities.fellow_id = fellows.id  
WHERE f.type in ('x', 'y', 'z') 
and auth.deactivated = false 
and DATE(activities.due_at) = current_date - INTERVAL '1 day' 
and activities.rating is not null

I am trying to run all the queries at once using a GUI. 我正在尝试使用GUI一次运行所有查询。 UNION and UNION ALL can only be used when the no of columns are same in the queries? 仅当查询中的列数相同时才能使用UNION和UNION ALL吗?

When I was using Toad I could run the sql queries if I include a delimiter such as ; 当我使用Toad时,如果包含定界符(如;),则可以运行sql查询。

I am not sure how this can be done in postgresql? 我不确定如何在postgresql中完成此操作?

Thank you. 谢谢。

Just pad the columns you don't have and union. 只需填充您没有的列并合并。 For instance: 例如:

select activities.type, sum(activity_fees.amount) 
...
Union
SELECT 'dummy', avg(activities.rating) 
....

Or just include activities.type since you have it available! 或者,只要包含activity.type,就可以使用它!

First, you probably don't need to run 14 different sets of queries. 首先,您可能不需要运行14组不同的查询。 If I had to guess, what changes is the interval. 如果我不得不猜测的话,间隔是什么变化。 I would suggest that you ask another question about how to simplify your overall process. 我建议您问另一个有关如何简化总体流程的问题。

If you want to bring results together using union all -- and union all is what you want for this -- then you need the same columns. 如果要使用union all合并结果-而union all是您想要的-那么您需要相同的列。 In addition, the date arithmetic can be optimized. 此外,可以优化日期算法。

You seem to have three columns in your data, so I would write this as: 您的数据中似乎包含三列,因此我将其写为:

select a.type, sum(af.amount) as amount, NULL as rating
from activity_fees af inner join
     activities a
     on af.activity_id = a.id 
where a.due_at >= current_date - interval '1 day' and
      a.due_at < current_date
group by a.type
union all
select NULL as type, NULL as amount, avg(au.rating)  as rating
from fellows f inner join
     auth au
     on au.a_id = f.id inner join
     activities a
     on a.fellow_id = f.id  
where f.type in ('x', 'y', 'z') and
      au.deactivated = false and
      a.rating is not null and
      (a.due_at >= current_date - INTERVAL '1 day' and
       a.due_at < current_date
      );

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

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