1

How to sum count value in SQL Server ?

I have table 1. I want to sum count value.

How to do that ?

SELECT Top 10 count(d.name) as countname,d.name as name ,sum(count(d.name)) as sumcount
FROM table 1 as d 
group by d.name order by count(d.name) desc

I want to display countname, name, sumcount. How to do that ?

3
  • 2
    Your question is hard to understand. Please put up test data (like make up data), as well as how you want the result set to look like after the query. Commented Jan 6, 2012 at 4:07
  • The 'sum' and 'count' will have the same value... If you count 10, the sum of 10 is... 10... Commented Jan 6, 2012 at 4:42
  • SELECT TOP 10 COUNT(*) AS countname, d.name FROM table 1 as d GROUP BY d.name ORDER BY COUNT(*) DESC will give you the top 10 most used d.name values as well as the number of times they're used. Commented May 18, 2020 at 5:57

3 Answers 3

4

Not sure I'm understanding your question, but if you're just looking to get the sum of all the count(d.name) values, then this would do that for you:

select sum(countname) as TotalCount
from
(
    SELECT Top 10 
        count(d.name) as countname,
        d.name as name
    FROM [table 1] as d  
    group by d.name 
    order by count(d.name) desc 
)a
Sign up to request clarification or add additional context in comments.

3 Comments

I want to display countname,name ,sumcount. how to do that ?
@JamSva I'm having a hard time understanding what you're looking for. Please edit your question with test data and the end result you're looking for. I'll be able to get a better idea from that.
@JamSva, assign the TotalCount to a variable, then include that in your original query. I'll do an answer that adds to this answer.
1

add with rollup to the end of your query

2 Comments

Will with rollup work with the order by clause in MS SQL? It doesn't in MySQL, which makes it hard to ensure you have the top number of occurrences of count(d.name) before adding them up.
Also, with MySQL and usage of a limit, the rollup doesn't work because the rollup result is added as a row to the end of the table. If you use a limit, you miss out on the final row, and the result of the rollup.
0

Expanding on the answer provided by @Shark, MySQL syntax will look like the following:

set @TotalCount = (select sum(countname) from (
    select count(d.name) as countname, d.name as name
    from table 1 as d
    group by name
    order by countname desc
    limit 10
) a);

select count(d.name) as countname, d.name as name, @TotalCount
FROM table 1 as d 
group by name 
order by countname desc
limit 10;

You may need to look up MS SQL syntax for setting local variables and limits.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.