开发者

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 a开发者_如何学Cnd 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?


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`)
}


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜