如何使用 min(date_field) 过滤数据 - postgres

How to filter data using min(date_field) - postgres

这是我获取申请人列表的查询,我要将申请人与另一个 table 认证申请者一起加入,我需要从那里找到 min(lic_exp_date) 认证申请者中的一个字段

SELECT cnctr.applicant AS applicant_id, cnctr.status, cnctr.hired_date, cnctr.systemuser, EXTRACT(DAY FROM now() - cnctr.hired_date) as probation_date,
apl.first_name, apl.last_name, apl.email, apl.address1, apl.city, applicant_state, apl.phone_number,
sysrole.name as role_name,
crtapl.lic_exp_date
FROM contractors cnctr
JOIN applicants apl ON apl.id = cnctr.applicant
JOIN contractorsrole crole ON crole.applicant_id = cnctr.applicant JOIN systemnurserole sysrole ON sysrole.id = crole.role_id
JOIN certificationsapplicants crtapl ON crtapl.applicant_id = cnctr.applicant JOIN certificationtypes crttype ON crttype.id = crtapl.certification_id
where cnctr.status = 44 

LIMIT 25 OFFSET 0

我需要的是我需要找到min(crtapl.lic_exp_date),每个申请者会有多个证书,我需要先找到过期的证书。我试图直接查询它,它有效,但当我与其他 tables.

加入申请人时它不起作用

错误是: 必须出现在 GROUP BY 子句中或用于聚合函数

此查询有效:

select min(cpl.lic_exp_date), cpl.applicant_id from certificationsapplicants cpl group by cpl.applicant_id

请大家帮忙

这应该可以解决问题(注意:未经测试的代码)

SELECT
    cnctr.applicant AS applicant_id,
    cnctr.status,
    cnctr.hired_date,
    cnctr.systemuser,
    EXTRACT(DAY FROM now() - cnctr.hired_date) as probation_date,
    apl.first_name,
    apl.last_name,
    apl.email,
    apl.address1,
    apl.city,
    applicant_state,
    apl.phone_number,
    sysrole.name as role_name,
    crtapl.lic_exp_date
FROM contractors cnctr
JOIN applicants apl ON apl.id = cnctr.applicant
JOIN contractorsrole crole ON crole.applicant_id = cnctr.applicant
JOIN systemnurserole sysrole ON sysrole.id = crole.role_id
JOIN certificationtypes crttype ON crttype.id = crtapl.certification_id
JOIN (
    SELECT
        MIN(cpl.lic_exp_date) AS lic_exp_date,
        cpl.applicant_id
    FROM certificationsapplicants cpl
    GROUP BY cpl.applicant_id
) crtapl ON crtapl.applicant_id = apl.id
WHERE cnctr.status = 44 

LIMIT 25 OFFSET 0

这是一个常见问题,已在此处得到很多解答。如果您需要更多详细信息,这里有几篇带有解释的好帖子。

  • must appear in the GROUP BY clause or be used in an aggregate function
  • GROUP BY / aggregate function confusion in SQL