【发布时间】:2017-06-16 16:36:31
【问题描述】:
我正在使用此查询来使用 postgresql 按最新日期查找唯一记录。我遇到的错误是“WHERE 中不允许使用聚合函数”。 How to fix error “aggregate functions are not allowed in WHERE” 在此链接之后,我尝试使用内部选择功能。但这没有用。请帮我编辑查询。我正在使用 PgAdmin III 作为客户端。
SELECT Distinct t1.pa_serial_
,t1.homeownerm_name
,t1.districtvdc
,t1.date as firstrancheinspection_date
,t1.status
,t1.name_of_data_collector
,t1.fulcrum_id
,first_tranche_inspection_v2_reporting_questionnaire.date_reporting
From first_tranche_inspection_v2 t1
LEFT JOIN first_tranche_inspection_v2_reporting_questionnaire ON (t1.fulcrum_id = first_tranche_inspection_v2_reporting_questionnaire.fulcrum_parent_id)
where first_tranche_inspection_v2_reporting_questionnaire.date_reporting = (
select Max(first_tranche_inspection_v2_reporting_questionnaire.date_reporting)
from first_tranche_inspection_v2
where first_tranche_inspection_v2.pa_serial_ = t1.pa_serial_
);
【问题讨论】:
-
在您的子查询中,您从
first_tranche_inspection_v2中进行选择,但 MAX 函数与first_tranche_inspection_v2_reporting_questionnaire中的字段相关。这是一个错字吗?或者你想在那里实现什么? -
是的,这是我的要求,所以我加入了这两个表
-
不,我的意思是 MAX 用于聚合相关表,因此您使用 MAX 的字段必须是该表的字段。事实并非如此,您没有在子查询中聚合表,而只是参考您必须在它之外确定的最大值。但是在子查询之外没有聚合。简而言之:你在这里做错了什么。问题是:你想做什么?
-
我想做的是 - pa_serial_、homeownerm_name、status..etc 等信息是从 first_tranche_inspection_v2 获得的,但其他几列是从 first_tranche_inspection_v2_reporting_questionnaire 获得的,我想根据 date_reporting 获取最新记录来自 first_tranche_inspection_v2_reporting_questionnaire 表,因为该表包含不同日期的相同信息,我需要获取唯一的最新记录
-
展示样本数据。
标签: sql postgresql