目前正在尝试在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
但我需要的是:
但同样,每个资产只能返回一个来自raproject的项目。
编辑: 预期的回报是:
name raproject_id current_status create_date
AssetA 405323966463460000 Review 07/10/2016 14:04
AssetB 405323966463412000 Monitoring 15/11/2013 11:26
答案 0 :(得分:1)
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]
}
要求