postgres:连接过滤中的动态子查询

时间:2017-01-17 11:51:30

标签: sql postgresql

目前正在尝试在Postgres中定义动态查询。本质上,Join中使用的子查询所做的过滤取决于每行的结果。我们的想法是查询中的每个“名称”只会根据一组特定的参数返回一个project_id。

没有任何过滤的基本查询:

SELECT a.name, rproj.raproject_id, rproj.current_status, rproj.create_date
FROM focalpoint fp
JOIN agl_asset a ON a.serial_number::text = fp."RoutineNumber"::text
JOIN agl_raproject AS rproj ON a.asset_id = rproj.asset_id 
JOIN agl_auditproject AS audit ON rproj.auditproject_id = audit.auditproject_id
ORDER BY a.name

那会回来:

name    raproject_id        current_status      create_date
AssetA  405323966463427000  Review              24/10/2014 18:35
AssetA  405323966463460000  Review              07/10/2016 14:04
AssetA  405323966463413000  Risk Identification 28/11/2013 14:16
AssetA  405323966463413000  Closed              21/11/2013 17:33
AssetB  405323966463412000  Monitoring          15/11/2013 11:26
AssetB  405323966463427000  Review              24/10/2014 18:35
AssetB  405323966463461000  Assessment          13/10/2016 10:32
AssetB  405323966463412000  Closed              15/11/2013 11:44

但我只想要每个资产一个“项目”。如果我只是试图获得基于create_date的“最新”,那将是:

SELECT a.name, rproj.raproject_id, rproj.current_status, rproj.create_date
FROM focalpoint fp
JOIN agl_asset a ON a.serial_number::text = fp."RoutineNumber"::text
JOIN agl_raproject AS rproj ON a.asset_id = rproj.asset_id AND rproj.create_date = ((SELECT max(rproj2.create_date) AS max
 FROM agl_raproject rproj2
 JOIN agl_auditproject audit ON rproj2.auditproject_id = audit.auditproject_id
 WHERE a.asset_id = rproj2.asset_id AND audit.project_type::text = 'ngERMAssessment'::text))
JOIN agl_auditproject AS audit ON rproj.auditproject_id = audit.auditproject_id
ORDER BY a.name

但我需要的是:

  1. 如果有任何项目,对于此特定资产,其中 current_status是“监控” - 返回该行
  2. 如果没有,请选择最新的(就像我上次查询时已经完成的那样)。
  3. 但同样,每个资产只能返回一个来自raproject的项目。

    编辑: 预期的回报是:

    name    raproject_id        current_status      create_date
    AssetA  405323966463460000  Review              07/10/2016 14:04
    AssetB  405323966463412000  Monitoring          15/11/2013 11:26
    

1 个答案:

答案 0 :(得分:1)

distinct on

order by

检查var list : [FeedbackRound] = [] list = try CoreDataInterface.sharedInstance.managedObjectContext.fetch(fetchRequest) as! [FeedbackRound] if let feedbackRoundArray:[FeedbackRound] = list { let arrRecordChunks:[FeedbackRound] = feedbackRoundArray[0...2] } 要求