Calculating and adding the totals row in Oracle for multiple columns
You can use CTE
and MATERIALIZE
hint to fetch the desired output as following:
with cte as (SELECT /*MATERIALIZE*/ <your query after select>)
select c.*
from cte c
union all
select null, null, null, sum(col2), sum(col3), sum(col4)
from cte;
The undocumented MATERIALIZE
hint uses global temporary table
so there will be no or little performance impact.
Cheers!!
How to SUM two fields within an SQL query
SUM
is an aggregate function. It will calculate the total for each group. +
is used for calculating two or more columns in a row.
Consider this example,
ID VALUE1 VALUE2
===================
1 1 2
1 2 2
2 3 4
2 4 5
SELECT ID, SUM(VALUE1), SUM(VALUE2)
FROM tableName
GROUP BY ID
will result
ID, SUM(VALUE1), SUM(VALUE2)
1 3 4
2 7 9
SELECT ID, VALUE1 + VALUE2
FROM TableName
will result
ID, VALUE1 + VALUE2
1 3
1 4
2 7
2 9
SELECT ID, SUM(VALUE1 + VALUE2)
FROM tableName
GROUP BY ID
will result
ID, SUM(VALUE1 + VALUE2)
1 7
2 16
Counting DISTINCT over multiple columns
If you are trying to improve performance, you could try creating a persisted computed column on either a hash or concatenated value of the two columns.
Once it is persisted, provided the column is deterministic and you are using "sane" database settings, it can be indexed and / or statistics can be created on it.
I believe a distinct count of the computed column would be equivalent to your query.
Is there a way to select sum on one column based on other DISTINCT column, while grouping by third column(date) only
You can aggregate and then aggregate again:
select max(year), sum(money), count(*)
from (select distinct year, money, id
from t
) t;
how to sum multiple rows with same id in SQL Server
Simple GROUP BY
and SUM
should work.
SELECT ID, NAME, SUM([NO])
FROM Your_TableName
GROUP BY ID, NAME;
Related Topics
Check If a Column Contains Text Using SQL
Storing Image in Database Directly or as Base64 Data
How to Split a Comma-Separated Value to Columns
How Select Max(Salary) of Employee Each Department With Employee_Id and Emp_Name
Query Takes a Very Long Time to Execute
How to Insert 1000 Rows At a Time
Hive Select Data into an Array of Structs
Percent to Total in Postgresql Without Subquery
When to Use Single Quotes, Double Quotes, and Backticks in MySQL
SQL Select Only Rows with Max Value on a Column
How to Return Pivot Table Output in MySQL
Select First Row in Each GROUP BY Group
Simulating group_concat MySQL Function in Microsoft SQL Server 2005
Retrieving the Last Record in Each Group - MySQL
Getting Student Name With Highest Total Mark in SQL
Remove Decimal Values Using SQL Query
Sql Merge Two Rows With Same Id But Different Column Values (Oracle)