Home > Database > Mysql Tutorial > How to Calculate the SUM of Grouped COUNTs in SQL?

How to Calculate the SUM of Grouped COUNTs in SQL?

Barbara Streisand
Release: 2024-12-23 01:09:18
Original
988 people have browsed it

How to Calculate the SUM of Grouped COUNTs in SQL?

Calculating SUM of Grouped COUNT in SQL Queries

In SQL, grouping data is essential for summarizing and analyzing large datasets. When working with grouped data, it can be useful to also calculate the sum of the grouped values. This article demonstrates how to achieve this using an example table and a practical SQL query.

Consider a table with two fields: ID and Name. Each record represents an individual, and multiple records can have the same name. We want to group the data by Name and count the number of records in each group. Additionally, we want to add a row at the end to display the total count of all records.

To achieve this, we can use the following SQL query:

SELECT name, COUNT(name) AS count, SUM(COUNT(name)) OVER() AS total_count
FROM Table
GROUP BY name;
Copy after login

Query Breakdown:

  1. SELECT clause: Selects the name field and calculates the count of records in each group (COUNT(name)) as count.
  2. SUM() OVER() clause: Calculates the sum of the count values for all groups using the SUM() function with the OVER() window function. This creates a new column called total_count.
  3. GROUP BY clause: Groups the results by the name field.

Results:

The query returns the following results:

Name Count Total Count
Alpha 1 6
Beta 3 6
Charlie 2 6
Name Count Total Count
Alpha 1 6
Beta 3 6
Charlie 2 6
SUM 6 6
SUM

6 6
The SUM row at the end displays the total count of all records, which is 6 in this example.

The above is the detailed content of How to Calculate the SUM of Grouped COUNTs in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template