0

I would like get the id and the number of id. So, I write this command sql:

SELECT count(id), id 
FROM tblExample

It's doesn't work. Have you a solution for me ? For to get the value of my id and the number of id.

Or a function PHP for count my resultset.

2
  • You want count of each ID or all ID? I assume the Id is unique in your table! Commented Feb 6, 2013 at 11:52
  • What RDBMS is this? Is it MySQL? Commented Feb 6, 2013 at 12:25

1 Answer 1

10

Just add a GROUP BY id:

SELECT id, COUNT(id)
FROM tblExample
GROUP BY id;

Demo


Update:

The query you posted:

SELECT count(id), id 
FROM tblExample;

Won't work in most of the RDBMS and it shouldn't. In SQL Server, you will got an error; saying that:

Column 'id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Strangely though, MySQL allow this(The OP didn't say what RDBMS he is using), and in this case, it will get an arbitrary value (this is also depends on an option to set), for the id column, and the COUNT in this case would be all the id's count.

But it is not recommended to do so.

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

3 Comments

Can you explain this behavior? I mean GROUP BY. Is it due to aggregate function COUNT?
@raheelshan - Yes, this is because of the COUNT function without a group by, see my edit.
@WhitneyR. - How it doesn't work? Can you please show me the exact query you tried, the errors you got if any? And if possible some sample data and the results that you want to get from these sample data.

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.