简体   繁体   中英

Grouping records from MySql

I've got two tables in MySql

1 (Staff): Id/Name/SecondName

2 (fee): Id/StaffId/Date(yyyy-mm-dd)/HoursWorked(hh:mm)/fee(int)/workType

There is also a script adding records to fee table.

I'm trying to group data in php to create html table like:

Name, Second Name | January 2009 | 123:45 hours | 2100,00 USD
February 2009...
March 2009 ....
Next person... etc.

So generally I'm trying to sum fee and hours in specific month and print a report from database...

And I need some advice/help... What is the bast way to create table like this?

I'm not 100% sure about this being perfect but it should definitely point you in the right direction. The AVG() function calls might be unnecessary.

SELECT 
Name,
SecondName,
SUM(fee.HoursWorked) as HoursWorked,
SUM(fee.fee) as fee,
YEAR(AVG(fee.Date)) as year,
MONTH(AVG(fee.Date)) as month
FROM Staff
JOIN fee ON staff.id = fee.staffid
ORDER BY fee.Date
GROUP BY staff.id, YEAR(fee.Date), MONTH(fee.Date)

Maybe something like this? Not tested though...

SELECT s.Name, s.SecondName, CONCAT(DAYOFMONTH(f.Date),', ',YEAR(f.Date)), 
SUM  (f.HoursWorked), SUM(f.Fee)
FROM Staff s
JOIN Fee f ON f.StaffId = s.Id
GROUP BY s.Id, YEAR(f.Date), MONTH(f.Date)  

Edit: Ofcourse you need to group on s.Id...

That's not the best way, but if you want to do it with one query (it's easy to export to Excel):

SELECT
  s.Name,
  s.SecondName,
  DATE_FORMAT('%M %y', f.`Date`),
  SEC_TO_TIME( SUM( TIME_TO_SEC( `HoursWorked` ) ) ) as TotalHours,
  sum(fee) AS TotalFee
FROM
  Staff AS s
  INNER JOIN fee AS f on s.id = f.StaffId
WHERE
  1
GROUP BY s.id, YEAR(f.`Date`), MONTH(f.`Date`)

You cal also query stuff:

// that's not a real function, just get all Staff into $staff
$staff = QueryRows(SELECT * FROM Staff);

and then query fee:

foreach($staff as $s){
  // use this query to query statistics
  SELECT * FROM fee
   WHERE StaffId = $s['id']
   GROUP BY StaffId, YEAR(f.`Date`), MONTH(f.`Date`)
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM