Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL SUM values of difference between two columns

I have two columns in one of my tables called TIME_OUT and TIME_IN. These are both decimal values. I basically want to sum the difference of these columns. I have the query below that outputs the difference with no issue, but I'd like to then SUM the difference:

SELECT (TIME_IN-TIME_OUT) AS DIFF FROM TABLE_timelogs WHERE YEAR(LOG_DATE) = YEAR(NOW());

+------+
| DIFF | 
+------+
| 10.0 |
|  4.0 |
|  3.0 |
+------+

Is there a way to integrate SUM into the query so that the ultimate output is 17.0? Thank you in advance!

like image 611
Jason Avatar asked Apr 01 '14 20:04

Jason


People also ask

How do I sum values from different columns 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.

How do I find the difference between two columns in MySQL?

Here's the generic SQL query to two compare columns (column1, column2) in a table (table1). mysql> select * from table1 where column1 not in (select column2 from table1); In the above query, update table1, column1 and column2 as per your requirement.

How do I sum multiple columns in MySQL?

Code: SELECT SUM(total_cost) FROM purchase WHERE cate_id='CA001'; Relational Algebra Expression: MySQL SUM() function retrieves the sum value of an expression which is made up of more than one columns.

Can I do a sum of a count in MySQL?

The SUM() function returns the total sum of a numeric column.


1 Answers

Add SUM to your query so the query reads:

SELECT SUM(TIME_IN-TIME_OUT) AS DIFF 
FROM TABLE_timelogs 
WHERE YEAR(LOG_DATE) = YEAR(NOW());

This adds the contents of the column 'diff'.

like image 108
Hank G Avatar answered Sep 18 '22 17:09

Hank G