在mysql中将Sum结果区分开来?

时间:2013-05-02 12:43:10

标签: mysql hibernate

这是我的代码

 select count(  model.voter.voterId),  


 SUM( CASE WHEN model.voter.age BETWEEN  :AGE18 and :AGE25 THEN 1 ELSE 0 END) as ageCount ,  
 SUM( CASE WHEN model.voter.age BETWEEN  :AGE26 and :AGE35 THEN 1 ELSE 0 END) as ageCount ,  
 SUM( CASE WHEN model.voter.age BETWEEN  :AGE36 and :AGE45 THEN 1 ELSE 0 END) as ageCount ,  
 SUM( CASE WHEN model.voter.age BETWEEN  :AGE46 and :AGE60 THEN 1 ELSE 0 END) as ageCount , 
 SUM( CASE WHEN model.voter.age > :AGE60 THEN 1 ELSE 0 END) as ageC  from User model  where  model.voter.voterId in(:voterIds) 

我通过了21个对象,但它只显示了22个结果  当我select count( distict model.voter.voterId)时它21但是结果仍然是22

我可以将总和条件区分开来吗?如何?

select count(uservoterd0_.voter_id) as col_0_0_, SUM(case when voter1_.age between 18 and 25 then 1 else 0 end) as col_1_0_, SUM(case when voter1_.age between 26 and 35 then 1 else 0 end) as col_2_0_, SUM(case when voter1_.age between 36 and 45 then 1 else 0 end) as col_3_0_, SUM(case when voter1_.age between 46 and 60 then 1 else 0 end) as col_4_0_, SUM(case when voter1_.age>60 then 1 else 0 end) as col_5_0_ from user_voter_details uservoterd0_ inner join voter voter1_ on uservoterd0_.voter_id=voter1_.voter_id where uservoterd0_.voter_id in (? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)

1 个答案:

答案 0 :(得分:0)

如果您传递了21个用户ID,但是从count()获得了22,那么您的数据中就会有重复的行。

尝试运行此查询以查看重复项的位置:

select cnt, count(*), min(voterId ), max(voterId)
from (select voterId, count(*) as cnt
      from user u
      group by voterId
     ) t
group by cnt
order by cnt desc