Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL- include sum of count(*) in single query

Using table i and the fields date_entered and code, I wrote a query to list a count for each year where code = '12A'.

select distinct year(date_entered) as Yr, count(*) as Cnt
from i
where code = '12A'
group by year(date_entered)
order by Yr desc

This produces:

Yr   |    Cnt
2011   |  780
2010   |  3489
2009   |  3256
...

I want to include a sum of the Cnt variable in my result set. I know how to find the sum using a separate query, but I would like to calculate the sum in my original query.

like image 300
Gary Avatar asked Apr 04 '11 15:04

Gary


People also ask

Can sum and count in same SQL query?

SQL SUM() and COUNT() using variable SUM of values of a field or column of a SQL table, generated using SQL SUM() function can be stored in a variable or temporary column referred as alias. The same approach can be used with SQL COUNT() function too.

How do I get the sum of a count in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.

What does count (*) do in SQL?

COUNT(*) returns the number of items in a group. This includes NULL values and duplicates. COUNT(ALL expression) evaluates expression for each row in a group, and returns the number of nonnull values.


1 Answers

Add WITH ROLLUP to the query after the GROUP BY clause and you'll get an extra row with a NULL Yr that contains your final total.

select year(date_entered) as Yr, count(*) as Cnt
from i
where code = '12A'
group by year(date_entered)
with rollup
order by Yr desc
like image 84
Joe Stefanelli Avatar answered Nov 15 '22 05:11

Joe Stefanelli