从MySql分组记录

时间:2011-03-29 10:50:36

标签: php mysql sql group-by

我在MySql中有两个表

  

1(员工):Id / Name / SecondName

     

2(费用):   ID / STAFFID /日期(YYYY-MM-DD)/ HoursWorked(HH:MM)/费(INT)/ workType

还有一个脚本将记录添加到费用表中。

我正在尝试在php中对数据进行分组以创建html表,如:

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

因此,一般情况下,我会尝试在特定月份汇总费用和小时数,并从数据库中打印报告......

我需要一些建议/帮助......这样创建表格的麻烦方法是什么?

3 个答案:

答案 0 :(得分:1)

我并非100%确定这是完美的,但它绝对应该指向正确的方向。可能不需要AVG()函数调用。

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)

答案 1 :(得分:1)

也许是这样的?虽未经过测试......

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)  

编辑:当然你需要分组s.Id ......

答案 2 :(得分:1)

这不是最好的方法,但是如果你想用一个查询来做(它很容易导出到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`)

你也可以查询东西:

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

然后查询费用:

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