I don't know how to combine and sum rows with same values from MySQL database with PHP language. I have database that has ID, Machine, Worker1, Worker2, Worker3, Hours1, Hours2, Hours3. For example if Worker1 is John than his hours are Hours1; if Worker2 is John than his hours are Hours2. Database contains a lot of workers and a lot of machines and this is just simple example:
table name = entry ID Machine Worker1 Worker2 Worker3 Hours1 Hours2 Hours3 1 M1 John Adam 5 7 2 M2 Adam Bruce 10 1 3 M1 Mark John 3 2 4 M1 John Marry Adam 8 9 6 ...
What I need is report like this to be selected from MySQL with PHP language to combine worker cells with same name in one cell and sum all his hours in one cell for the selected Machine:
Machine = M1 ----------------------------- Worker Hours John 15 Adam 13 Mark 3 Marry 9 ------------------------ Total; 40
I appreciate for your help and time.
You need to use the group by in your sql.
SELCT SUM(Hours1),Worker1 FROM table_name WHERE Machine='M1' GROUP BY Worker1
You might also want to check http://www.w3schools.com/sql/sql_groupby.asp
select worker, sum(Hour) as Hours from
(select sum(Hours1) as Hour,Worker1 as Worker from entry where Machine='M1' group by Worker1
UNION
select sum(Hours2) as Hour,Worker2 as Worker from entry where Machine='M1' group by Worker2 UNION
select sum(Hours3) as Hour ,Worker3 as Worker from entry where Machine='M1' group by Worker3) t1
where worker IS NOT NULL group by Worker ORDER BY Hours DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.