【问题标题】:How to filter data using min(date_field) - postgres如何使用 min(date_field) 过滤数据 - postgres
【发布时间】:2020-07-04 15:44:12
【问题描述】:

这是我获取申请者列表的查询,我正在将申请者与另一个表certificationsapplicants 一起加入,从那里我需要在certificationsapplicants 中找到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),每个申请人都会有多个证书,我需要先找到过期的证书。我尝试直接查询它,它可以工作,但是当我将申请人与其他表连接时它不工作。

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

这个查询有效:

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

请大家帮忙。

【问题讨论】:

    标签: postgresql aggregate-functions outer-join


    【解决方案1】:

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

    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
    

    这是一个常见问题,已在此处得到大量解答。如果您想了解更多详细信息,这里有几篇很好的帖子,其中包含解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 2014-06-25
      • 2019-10-09
      相关资源
      最近更新 更多