본문으로 바로가기

[JPA] 여러 개 컬럼 Sum을 조회하는 방법은 없다

category JAVA/JPA 2022. 2. 17. 00:30

목적

JPA 에서 한 쿼리로 여러 개 컬럼 Sum 값을 불러오기 위함.

1
2
3
4
5
6
    //    날짜/시간별 통계 데이터 
    @Query(value = 
            " SELECT SUM(req_cnt) AS req_cnt, SUM(res_cnt) AS res_cnt, SUM(ctr_cnt) AS ctr_cnt"+ 
            " FROM AdStatistics " + 
            " WHERE coldate = :col_date")
    Optional<AdStatistics> sumAdStatisticsByColdate(@Param("col_date"String col_date);
cs

쿼리를 위와 같이 사용했으나 안되었다. 

https://stackoverflow.com/questions/3449719/how-to-run-an-aggregate-function-like-sum-on-two-columns-in-jpa-and-display-thei

방법이 있는 것 같으나 내가 원하는 방식대로는 안 되는 것 같다.

 

해결

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    @Query(value = 
            " SELECT SUM(req_cnt) AS req_cnt"+ 
            " FROM AdStatistics " + 
            " WHERE coldate = :col_date")
    int sumReqCntByColdate(@Param("col_date"String col_date);
    
    @Query(value = 
            " SELECT SUM(res_cnt) AS res_cnt"+ 
            " FROM AdStatistics " + 
            " WHERE coldate = :col_date")
    int sumResCntByColdate(@Param("col_date"String col_date);
    
    @Query(value = 
            " SELECT SUM(ctr_cnt) AS ctr_cnt"+ 
            " FROM AdStatistics " + 
            " WHERE coldate = :col_date")
    int sumCtrCntByColdate(@Param("col_date"String col_date);
    
    List<AdStatistics> findAllByColdateAndColhour(String col_date, String col_hour);
cs

그냥 각각 sum 하여 불러왔다.

일단 해결은 했으나 나중에 해법을 찾아봐야겠다. 찝찝하다.

혹시나 해결 방법이 있으시다면 댓글 달아주세요.