MySQL:Sum()和Count在一个查询中?

时间:2016-07-09 14:28:19

标签: php mysql sql

我在SQL查询中使用sum()和count()寻求帮助:

select s1_s2,count(s1_s2) as RES 
from city_user 
where s1_s2 in (select s1_s2 from city_user ) 
group by s1_s2

结果:Image Query Result

我想为RES列生成sum()

这可能吗?

4 个答案:

答案 0 :(得分:1)

要选择单个s1_s2值的计数,以下查询可能有所帮助

select s1_s2, count(s1_s2) as res 
from city_user 
group by s1_s2;

要获取res列的 sum ,以下查询可能会有所帮助

select sum(res) as sum 
from 
    (select s1_s2, count(s1_s2) as res 
     from city_user 
     group by s1_s1) 
city_user;

相同
select count(s1_s2) as count 
from city_user;

原因:这是因为您尝试根据s1_s2对列进行分组并获取其计数并将其存储为Res列并计算其总和与行数相同对于表中的s1_s2。

答案 1 :(得分:0)

可能你可以使用下面的外部查询,同样你的WHERE条件没有意义,因为你的IN子句从同一个表中获取列s1_s2的所有值,这将永远是真的

select *, SUM(RES) as SUM_RES
FROM (
select s1_s2,
count(s1_s2) as RES 
from city_user 
group by s1_s2) xxx

答案 2 :(得分:0)

您的查询毫无意义。 where s1_s2 in (select s1_s2 from city_user )只是写where s1_s2 is not null的一种复杂且极其低效的方式。

RES列的总和基本上是city_user中所有行的计数,或者至少是city_users1_s2不为空的行。为了将来需要阅读您的查询的人,包括您自己,请进行两次查询:

select s1_s2,count(s1_s2) as RES 
from city_user 
where s1_s2 is not null
group by s1_s2

select count(*)
from city_user
where s1_s2 is not null

答案 3 :(得分:0)

thanks for your answers

this what I wanted:

look this pic : result

this query works fine for me:

select s1_s2,
count(s1_s2) as res,
(select sum(res) as sum from (
  select s1_s2, count(s1_s2) as res from city_user group by s1_s2) city_user) as Sum_RES from city_user  group by s1_s2