Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 如何将多个select结果合并到一个表中?_Postgresql - Fatal编程技术网

Postgresql 如何将多个select结果合并到一个表中?

Postgresql 如何将多个select结果合并到一个表中?,postgresql,Postgresql,我有一个查询,它从同一个表中返回每月平均值,但针对不同的压力水平: SELECT some_id, avg(exposure_value) monthly_avg_1000 FROM mytable WHERE pressure_level = 1000 AND some_id = 7 GROUP BY some_id, date_trunc('month', measurement_time) 然后我有相同的问题,但压力水平不同: SELECT some_id, avg(exposure_v

我有一个查询,它从同一个表中返回每月平均值,但针对不同的压力水平:

SELECT some_id, avg(exposure_value) monthly_avg_1000
FROM mytable
WHERE pressure_level = 1000
AND some_id = 7
GROUP BY some_id, date_trunc('month', measurement_time)
然后我有相同的问题,但压力水平不同:

SELECT some_id, avg(exposure_value) monthly_avg_925
FROM mytable
WHERE pressure_level = 925
AND some_id = 7
GROUP BY some_id, date_trunc('month', measurement_time)
两个查询都返回12行(每月1行),其中包含ID和当月的平均值:

some_id | monthly_avg_1000
--------------------------
1       | 0.000023 
1       | 0.000051 
1       | 0.000009 

some_id | monthly_avg_925
--------------------------
1       | 0.000014 
1       | 0.000007 
1       | 0.000131
我想将这两个查询组合起来,以便每月平均值列都出现在最终的表中:

some_id | monthly_avg_1000 | monthly_avg_925
--------------------------
1       | 0.000023         | 0.000014 
1       | 0.000051         | 0.000007 
1       | 0.000009         | 0.000131

我如何才能做到这一点?

如果您有相同的id,那么您可以尝试加入:

with a as (
SELECT some_id, avg(exposure_value) monthly_avg_1000,date_trunc('month', measurement_time) d
FROM mytable
WHERE pressure_level = 1000
AND some_id = 7
GROUP BY some_id, date_trunc('month', measurement_time)
)
, b as (
SELECT some_id, avg(exposure_value) monthly_avg_925, date_trunc('month', measurement_time) d
FROM mytable
WHERE pressure_level = 925
AND some_id = 7
GROUP BY some_id, date_trunc('month', measurement_time)
) 
select distinct a.some_id, monthly_avg_1000,monthly_avg_925 
from a
join b on a.some_id = b.some_id and a.d = b.d

为什么不加入两个CTE?。。他们有相同的ID-对吗?。@VaoTsun我对postgressql和数据库不太熟悉-我甚至不知道CTE是什么:)P.S是的,相同的ID。这是最简单的方法-不分析结构和查询。检查我的答案,如果它像我预期的那样工作,我会得到12行(每月1行),但是我得到了144行(12*12)-使用您的query.hm-distinct有帮助吗?。。看,我需要结构:)是的,我提供了一个ID,所以ID是一样的。太好了,谢谢。这很有效。我真不敢相信仅仅是添加列就这么复杂!