2014-04-19 91 views
0

即時尋找在這個有點幫助,我是一個有點迷糊命名查詢摸出平均

我創建了存儲標記爲用戶

基本上我想創建一個命名查詢到實體使用和一個自動工作了平均水平,唯一的問題是我只想要一個選擇的列進行平均

目前該表是:

@Entity(name = "MARKING") 
public class Marking implements Serializable { 

    private static final long serialVersionUID = 1L; 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    @ManyToOne 
    private Person marker; 

    @ManyToOne 
    private Project project; 


    private String markingCompleted, markSectionOne, markSectionTwo, markSectionThree, markSectionFour, 
      markSectionFive, markSectionSix, markSectionSeven, markSectionEight, 
      markSectionNine, markSectionTen, markSectionEleven, markSectionTwelve, markSectionThirteen, markAdjust, overalMark, thirdMarker, plagorism; 

什麼,我爲我王,是我應該如何組織查詢,只會制定出平均markingSectionOne - 十三

謝謝你們

編輯

我已經加入到這個我的門面,但它似乎不正確的是它呢?

public TypedQuery<Double> markingAvg(Project id) { 
    System.out.println("id = " + id); 
    TypedQuery<Double> query = 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)/13.0) from Marking m where m.project = :id", Double.class); 
    query.setParameter("id", id); 
    double avg = query.getSingleResult(); 
    return null; 
} 

回答

2

第一種方法是在數據庫方面,計算平均值,然後檢索結果:

TypedQuery<Double> query = em.createQuery("select ((m.markSectionOne + ... + m.markSectionThirteen)/13.0) from Marking m where m.id = :id", Double.class); 
query.setParameter.... 
double avg = query.getSingleResult(); 

另一種方式是選擇你的實體,然後在Java中計算平均:

TypedQuery<Marking> query = em.createQuery("select m from Marking m where m.id = :id", Marking.class); 
query.setParameter.... 
Marking m = query.getSingleResult(); 
int sum = m.getMarkSectionOne() + ... + m.getMarkSectionThirteen(); 
double avg = sum/13.0; 
+0

莫非你檢查編輯我對我的問題是這樣嗎? – user2061913

+0

它看起來像你想'GROUP BY'項目。 – MGorgon