SQL - Add Up All Row-Values of One Column in a Singletable

SQL - Add up all row-values of one column in a singletable

SELECT SUM(size) AS overallSize FROM table WHERE bla = 5;

Add up all the values in a column

If you just want to get the sum of all counts you can use this:

SELECT SUM(CallCount) FROM MyTbl;

If you want the total together with the other values you can use the OVER clause:

SELECT *, SUM(CallCount)OVER()
FROM MyTbl;

SQL Query to Add Values from Column X for Every Entry That Has Y

This is a simple GROUP BY query, I'm not sure what's confusing you.

SELECT x, SUM(z) total_z
FROM table
WHERE y = 123
GROUP BY x

MySQL - sum column value(s) based on row from the same table

I think you're making this a bit more complicated than it needs to be.

SELECT
ProductID,
SUM(IF(PaymentMethod = 'Cash', Amount, 0)) AS 'Cash',
-- snip
SUM(Amount) AS Total
FROM
Payments
WHERE
SaleDate = '2012-02-10'
GROUP BY
ProductID

sql - getting sum of same column from multiple tables

You can achieve it using Coalesce as follows

SELECT 
(SELECT coalesce(SUM(value),0) FROM table1) +
(SELECT coalesce(SUM(value),0) FROM table2) +
(SELECT coalesce(SUM(value),0) FROM table3) as total_sum

Another approach is to use union all to merge all values into single table

select distinct coalesce(sum(a.value), 0) as total_sum from
(select value from table1
union all
select value from table 2
union all
select value from table 3) a;

SQL Sum amount for column with unique values

As per explanation you provided, I think your requirement is aggregate revenue of selective records that map with another table based on Col2 values. If that is the case then you may try following query.

WITH
rev_calc AS (
SELECT
distinct(Col2) as Col2
From table_input
LEFT JOIN another_table
ON another_table.Col2 = table_input.Col2
)
SELECT
Col0,
Col1,
SUM(Revenue) AS total_revenue
FROM table_input
WHERE Col2 in (select Col2 from rev_calc)
GROUP BY Col0, Col1;

Sum multiple column with PARTITION from single table

You want to group together rows that belong to the same EmployeeID, so this implies aggregation rather than window functions:

SELECT
OT.EmployeeId,
CONVERT(TIME, DATEADD(MS, SUM(DATEDIFF(MS, '00:00:00.000', OT.HourMargin)), '00:00:00.000')) AS TotalMargin,
SUM(OT.OvertimePoint) AS TotalPoint,
COALESCE(SUM(OLC.OLC), 0) AS TotalOLC,
COALESCE(SUM(OLC.Trip), 0) AS TotalTrip
FROM @Overtime OT
LEFT JOIN @OLC OLC ON OLC.EmployeeId = OT.EmployeeId
GROUP BY OT.EmployeeId

I also don't see the point for the join condition on the dates, so I removed it. Finally, you can use coalesce() to return 0 for rows that have no OLC.

Demo on DB Fiddle:


EmployeeId | TotalMargin | TotalPoint | TotalOLC | TotalTrip
---------: | :---------- | ---------: | -------: | --------:
1 | 08:00:00 | 24 | 4 | 0
2 | 04:00:00 | 12 | 0 | 0
3 | 04:00:00 | 12 | 6 | 12


Related Topics



Leave a reply



Submit