diff --git a/src/main/java/com/divudi/bean/common/DataAdministrationController.java b/src/main/java/com/divudi/bean/common/DataAdministrationController.java index 68a082211d..e9982cea4b 100644 --- a/src/main/java/com/divudi/bean/common/DataAdministrationController.java +++ b/src/main/java/com/divudi/bean/common/DataAdministrationController.java @@ -4886,13 +4886,20 @@ public void setMissingFields(Set missingFields) { public void dischargeOldDuplicateEncounters() { try { String t = patientEncounterFacade.getTableName(); + String pr = patientRoomFacade.getTableName(); + // Group by the actual room (roomFacilityCharge_id in patientroom), not by the + // PatientRoom assignment ID. Multiple PatientRoom records can point to the same + // physical room, so grouping by currentPatientRoom_id only catches duplicates + // within the same assignment, not across different admissions to the same room. String sql = "UPDATE " + t + " pe " + + "JOIN " + pr + " prm ON pe.currentPatientRoom_id = prm.id " + "JOIN ( " - + " SELECT MAX(id) AS keep_id, currentPatientRoom_id " - + " FROM " + t + " " - + " WHERE discharged = 0 AND paymentFinalized = 0 AND currentPatientRoom_id IS NOT NULL " - + " GROUP BY currentPatientRoom_id " - + ") latest ON pe.currentPatientRoom_id = latest.currentPatientRoom_id " + + " SELECT MAX(pe2.id) AS keep_id, prm2.roomFacilityCharge_id " + + " FROM " + t + " pe2 " + + " JOIN " + pr + " prm2 ON pe2.currentPatientRoom_id = prm2.id " + + " WHERE pe2.discharged = 0 AND pe2.paymentFinalized = 0 AND pe2.currentPatientRoom_id IS NOT NULL " + + " GROUP BY prm2.roomFacilityCharge_id " + + ") latest ON prm.roomFacilityCharge_id = latest.roomFacilityCharge_id " + "SET pe.discharged = 1 " + "WHERE pe.discharged = 0 AND pe.paymentFinalized = 0 " + "AND pe.id != latest.keep_id "