postgresql在单个查询中运行具有不同列的多个select语句

时间:2015-06-18 22:26:25

标签: sql postgresql

我有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

我正在尝试使用GUI一次运行所有查询。 UNION和UNION ALL只能在查询中没有列相同时使用

当我使用Toad时,如果我包含一个分隔符,我可以运行sql查询;

我不确定如何在postgresql中完成这项工作?

谢谢。

2 个答案:

答案 0 :(得分:1)

只需填充您没有的列和联合。例如:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

或者只是包含activities.type,因为你可以使用它!

答案 1 :(得分:1)

首先,您可能不需要运行14组不同的查询。如果我不得不猜测,间隔会发生什么变化。我建议您询问另一个问题,了解如何简化整个过程。

如果您想使用union all将结果放在一起 - 而union all就是您想要的 - 那么您需要相同的列。此外,可以优化日期算术。

您的数据中似乎有三列,因此我将其写为:

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
      );
相关问题