I'm looking for help using sum() and count () in my SQL query:
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
Is that possible?
To select the count of individual s1_s2 values the following query may help
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
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.
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
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
.
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. 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
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.