简体   繁体   中英

How to not GROUP BY column when param of column is NULL in 'JPA Query'?

I want select data from table and GROUP BY with city_id, district_id, ward_id. And if one of these column have param is null then GROUP BY the remaining columns.

Example: If param:ward_id is null, then GROUP BY columns city_id, district_id. And column ward_id not affect to GROUP BY. Thanks.

Edit: I add sum(people) and filter year in query.

@Query(value = "SELECT city_id, district_id, ward_id, sum(people) as sum_people
        FROM table  
        WHERE (:city_id is null OR city_id =:city_id ) 
        AND (:district_id is null OR district_id =:district_id ) 
        AND (:ward_id is null OR ward_id =:ward_id ) 
        AND year =:year
        GROUP BY city_id, district_id, ward_id",
        nativeQuery = true)
List<Object> findAddress(
        @Param("city_id") Integer city_id,
        @Param("district_id") Integer district_id,
        @Param("ward_id") Integer ward_id,
        @Param("year") Integer year
    )
SELECT * FROM table

You are not performing any aggregation.

WHERE (:city_id is null OR city_id =:city_id ) 
AND (:district_id is null OR district_id =:district_id ) 
AND (:ward_id is null OR ward_id =:ward_id ) 

You are also filtering data based on these 3 columns.

So the answer is to remove the group by altogether. If you want to control the ordering of your output, use ORDER BY instead.


After the edit, you included sum(people).

Try the following - note that I have not tested.

SELECT SELECT city_id, district_id, ward_id, sum(people) as sum_people
FROM (SELECT city_id, district_id, case :ward_id is null then '' else ward_id end ward_id, people
    FROM table
    WHERE (:city_id is null OR city_id =:city_id ) 
    AND (:district_id is null OR district_id =:district_id ) 
    AND (:ward_id is null OR ward_id =:ward_id )
) tmp
GROUP BY city_id, district_id, ward_id END

Essentially, when you use the null to filter on ward_id, it will replace the results with '' so that the group by will aggregate all ward_ids.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM