61

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 
2
  • 1
    Are there any columns in your table? You want to count SID group by SID? hmm.... +1 to @bluefeet I too guess it's max count of (SID) for that date... but guess his comment is gone.. Commented Dec 12, 2012 at 10:33
  • 1
    I have to count the rows! count(2,3,4,3) Commented Dec 12, 2012 at 10:34

3 Answers 3

98

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can anyone explain why you need the aliases? I tried it without them and it didn't work, but it's not obvious to me that you need them considering you never use them ('tot' and 'src' in this case) in the query.
@GarrettDisco Since you are using a subquery, each column in the subquery needs to have a name aka an alias. SQL Server also requires an alias on subqueries.
11

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'

3 Comments

@SigiAnonym, I don't have SQL Server to test. But does the updated version work?
@dan1111 try SQLFIDDLE ;) on the web.
do i need to add the colums at the end of the command and the alias ?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.