简体   繁体   English

当“JPA 查询”中列的参数为 NULL 时,如何不 GROUP BY 列?

[英]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.我想要 select 数据来自表和 GROUP BY 与 city_id、district_id、ward_id。 And if one of these column have param is null then GROUP BY the remaining columns.如果这些列之一的参数是 null 然后 GROUP BY 其余列。

Example: If param:ward_id is null, then GROUP BY columns city_id, district_id.示例:如果 param:ward_id 为 null,则 GROUP BY 列 city_id、district_id。 And column ward_id not affect to GROUP BY.并且列 ward_id 不影响 GROUP BY。 Thanks.谢谢。

Edit: I add sum(people) and filter year in query.编辑:我在查询中添加 sum(people) 和过滤年份。

@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.您还根据这 3 列过滤数据。

So the answer is to remove the group by altogether.所以答案是完全删除组。 If you want to control the ordering of your output, use ORDER BY instead.如果您想控制 output 的排序,请改用 ORDER BY。


After the edit, you included sum(people).编辑后,您包括 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.本质上,当您使用 null 过滤 ward_id 时,它将用 '' 替换结果,以便 group by 将聚合所有 ward_id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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