Reputation: 920
should be simple one but i am currently really confused
i have a db query :
public double markingAvg(Marking id) {
System.out.println("In MarkingAvg");
System.out.println("id = " + id);
System.out.println("id = " + id.getId());
Query m = em.createQuery("SELECT m.markSectionOne, m.markSectionTwo, m.markSectionThree, m.markSectionFour, m.markSectionFive, m.markSectionSix, m.markSectionSeven, m.markSectionEight, m.markSectionNine, m.markSectionTen, m.markSectionEleven, m.markSectionTwelve, m.markSectionThirteen FROM MARKING m WHERE m.id = :id", Double.class);
m.setParameter("id", id.getId()); // Note the getId()
System.out.println(m);
List<Object[]> allMarks = m.getResultList();
double total = 0.0;
int count = 0;
for (Object[] marks : allMarks) {
for (Object mark : marks) {
total += Double.parseDouble((String) mark);
++count;
}
}
return total / (double) count;
}
which just gets the values from the 13 columns and does the average on them, however it breaks when there is a null value in them, is there any way to say if there is a null value from any of the columns to return the total to be 0? Thanks
Upvotes: 0
Views: 1643
Reputation: 547
You could also handle this in your query: E.g.:
ij> CREATE TABLE T(I INT);
ij> INSERT INTO T VALUES 1, 2, 3, NULL;
4 rows inserted/updated/deleted
ij> SELECT * FROM T;
I
-----------
1
2
3
NULL
4 rows selected
ij> SELECT (CASE WHEN I IS NULL THEN 0 ELSE I END) FROM T;
1
-----------
1
2
3
0
4 rows selected
In your case it might be even better to calculate the average in SQL
ij> SELECT AVG(CAST(I AS DOUBLE)) AS AVERAGE FROM T;
AVERAGE
------------------------
2.0
WARNING 01003: Null values were eliminated from the argument of a column function.
1 row selected
Note the warning. If you actually want the NULLs to count as 0 in the average you have to use the CASE expression mentioned above.
Upvotes: 1
Reputation: 1168
You could use inline conditional check for this:
total += Double.parseDouble((String) ((mark==null) ? 0 : mark)));
Upvotes: 2
Reputation: 1731
Change your query to the following:
SELECT NVL(m.markSectionOne,0),
NVL(m.markSectionTwo,0),
NVL(m.markSectionThree,0),
NVL(m.markSectionFour,0),
NVL(m.markSectionFive,0),
NVL(m.markSectionSix,0),
NVL(m.markSectionSeven,0),
NVL(m.markSectionEight,0),
NVL(m.markSectionNine,0),
NVL(m.markSectionTen,0),
NVL(m.markSectionEleven,0),
NVL(m.markSectionTwelve,0),
NVL(m.markSectionThirteen,0)
FROM MARKING m WHERE m.id = :id;
Upvotes: 0