Select count(*) from result query

SqlSql ServerSelect

Sql Problem Overview


I need help from you, this is my sql query:

select count(SID) 
from Test 
where Date = '2012-12-10' 
group by SID

this is my result:

|2|
|3|
|4|
|3|

and now I have to count the results from first query!

Expected result: 4 

Sql Solutions


Solution 1 - Sql

You can wrap your query in another SELECT:

select count(*)
from
(
  select count(SID) tot  -- add alias
  from Test 
  where Date = '2012-12-10' 
  group by SID
) src;  -- add alias

See SQL Fiddle with Demo

In order for it to work, the count(SID) need a column alias and you have to provide an alias to the subquery itself.

Solution 2 - Sql

This counts the rows of the inner query:

select count(*) from (
    select count(SID) 
    from Test 
    where Date = '2012-12-10' 
    group by SID
) t

However, in this case the effect of that is the same as this:

select count(distinct SID) from Test where Date = '2012-12-10'

Solution 3 - Sql

select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)

should works

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionButtersView Question on Stackoverflow
Solution 1 - SqlTarynView Answer on Stackoverflow
Solution 2 - Sqldan1111View Answer on Stackoverflow
Solution 3 - SqlDaniel MácsView Answer on Stackoverflow