Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting group by sum and total sum in a single query

Tags:

mysql

People also ask

Can we use sum with GROUP BY?

SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group. It is better to identify each summary row by including the GROUP BY clause in the query resulst.

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 sum by GROUP BY data in SQL?

The SQL GROUP BY Statement The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

Can I have GROUP BY and ORDER BY together in SQL query?

Both GROUP BY and ORDER BY are clauses (or statements) that serve similar functions; that is to sort query results. However, each of these serve very different purposes; so different in fact, that they can be employed separately or together.


use ROLLUP with your query.

The GROUP BY clause permits a WITH ROLLUP modifier that causes extra rows to be added to the summary output.

SELECT category_id,SUM(price) as totalprice
FROM products 
GROUP BY category_id WITH ROLLUP

SELECT category_id, SUM(price) as totalprice
FROM products 
GROUP BY category_id WITH ROLLUP

Check out the page in the manual