简体   繁体   English

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

[英]MySQL: Sum () and Count in one query?

I'm looking for help using sum() and count () in my SQL query:我正在寻找在我的 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

result: Image Query Result结果:图片查询结果

I want to make sum () for RES column我想为 RES 列制作 sum()

Is that possible?那可能吗?

To select the count of individual s1_s2 values the following query may help要选择单个 s1_s2 值的计数,以下查询可能会有所帮助

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

To obtain the sum of res column the following query may help要获得 res 列的总和,以下查询可能会有所帮助

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

which is the same as这与

select count(s1_s2) as count 
from city_user;

Reason : It's because you are trying to group the column based on s1_s2 and obtain its count and store it as Res column and calculate its sum which is same as the number of rows for s1_s2 in the table.原因:这是因为您试图根据 s1_s2 对列进行分组并获取其计数并将其存储为Res列并计算其总和,该总和与表中 s1_s2 的行数相同。

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

Probably you can use a outer query like below, again your WHERE condition makes no sense as your IN clause takes all values of column s1_s2 from same table which will always be true可能你可以使用像下面这样的外部查询,同样你的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

Your query makes little sense.您的查询毫无意义。 where s1_s2 in (select s1_s2 from city_user ) is just a complicated and REALLY inefficient way of writing where s1_s2 is not null . where s1_s2 in (select s1_s2 from city_user )只是一种复杂且非常低效的写入方式, where s1_s2 is not null

The sum of the RES column is basically the count of all rows in city_user , or at least those rows in city_user for which s1_s2 is not null. RES列的总和基本上是city_user中所有行的计数,或者至少是city_users1_s2不为空的那些行。 For the sake of people that need to read your queries in the future, including yourself, make it two queries:为了将来需要阅读您的查询的人,包括您自己,将其设为两个查询:

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

and

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

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

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