MySQL want to sum of two columns with UNION

I have two MySQL tables. Each table has the following fields:

I want to sum of the hours and minutes field of these two tables for a p_id or project_id. Below query did not provide me the expected result.

SELECT SUM(hours_value), SUM(minute_value)
    FROM timesheet_master 

    UNION 
    SELECT `hours_value` 
    FROM timesheet_master_archive
    WHERE `p_id` = '1'

Upvotes: 0

Views: 58

Answers (3)

The query I found:

SELECT SUM(hours_value) as hrval, SUM(minute_value) as minval
FROM timesheet_master WHERE `p` = '1'
UNION 
SELECT `hours_value`,minute_value
FROM timesheet_master_archive WHERE `p_id` = '1'

Upvotes: 0

Thorsten Kettner
Thorsten Kettner

Reputation: 94884

I suppose you want to union the rows and then calculate the sums? That would be:

select sum(hours_value), sum(minute_value)
from 
(
  select hours_value, minute_value from t1 where p_id = 1
  union all
  select hours_value, minute_value from t2 where p_id = 1
) both_tables;

Upvotes: 3

Fahmi
Fahmi

Reputation: 37473

You can try below - for union, your no of columns should be equal in both select query

SELECT SUM(hours_value) as hrval, SUM(minute_value) as minval
FROM timesheet_master 
UNION 
SELECT `hours_value`,minute_value
ROM timesheet_master_archive WHERE `p_id` = '1'

Upvotes: 2

Related Questions