Pruebalo en https://www.jdoodle.com/execute-sql-online/
create table risk_test(risk_test_date date, id_risk int);
insert into risk_test values('2020-10-12 20:38:29', 1);
insert into risk_test values('2020-10-12 19:48:29', 1);
insert into risk_test values('2020-10-12 16:18:00', 1);
insert into risk_test values('2020-10-12 19:38:29', 2);
insert into risk_test values('2020-10-11 19:39:29', 2);
insert into risk_test values('2020-10-13 19:31:29', 2);
insert into risk_test values('2020-10-02 19:31:29', 3);
insert into risk_test values('2020-10-01 19:32:29', 3);
insert into risk_test values('2020-10-04 19:39:29', 3);
select max(risk_test_date),id_risk from risk_test group by id_risk;
Ya tenemos la query que nos va ha proporcionar los datos deseados, ahora toca obtener-lo con JAVA.
Primero crear una clase Entidad que define al registro en base de datos:
Class Risk {
private int id_risk_test;
private String risk_impact_result;
private String risk_impact_evaluation;
private String risk_prob_result;
private String risk_prob_evaluation;
private java.util.Date risk_test_date;
private int id_risk;
public String getRisk_impact_result(){
return risk_impact_result;
}
public void setRisk_impact_result(String risk_impact_result){
this.risk_impact_result=risk_impact_result;
}
public String getRisk_impact_evaluation(){
return risk_impact_evaluation;
}
public void setRisk_impact_evaluation(String risk_impact_evaluation){
this.risk_impact_evaluation=risk_impact_evaluation;
}
public String getRisk_prob_result(){
return risk_prob_result;
}
public void setRisk_prob_result(String risk_prob_result){
this.risk_prob_result=risk_prob_result;
}
public String getRisk_prob_evaluation(){
return risk_prob_evaluation;
}
public void setRisk_prob_evaluation(String risk_prob_evaluation){
this.risk_prob_evaluation=risk_prob_evaluation;
}
public java.util.Date getRisk_test_date(){
return risk_test_date;
}
public void setRisk_test_date(java.util.Date risk_test_date){
this.risk_test_date=risk_test_date;
}
public int getId_risk_test(){
return id_risk_test;
}
public void setId_risk_test(int id_risk_test){
this.id_risk_test=id_risk_test;
}
public int getId_risk(){
return id_risk;
}
public void setId_risk(int id_risk){
this.id_risk=id_risk;
}
}
Ahora ejecutar la query:
private static String SQL = "select max(risk_test_date),id_risk from risk_test group by id_risk";
...
private List<Risk> getRisk()
{
List<Risk> results = new ArrayList<>();
try
{
PreparedStatement statement = connection.prepareStatement(SQL);
ResultSet rs = statement.executeQuery(SQL);
while(rs.next()) {
Risk aRisk= new Risk();
aRisk.setIdRiskTest(rs.getInteger("id_risk_test"));
...
results.add(aRisk);
}
}
catch(SQLException e) {
// log any exceptions ...
}
finally() {
// always close your JDBC resources - google it
// example
try{
if (statement != null) {
statement.close();
statement=null;
}
}
catch(SQLException e) {
// couldn't close statement
}
...
}
return results;
}