每周一组的总和并放入数组

时间:2017-02-17 20:02:28

标签: php mysql select group-by dayofweek

我有一张存储劳动力数据的表格。其中一列是特定项目的工作小时数(rthours),另一列是日期(labor_date)。

我需要获取当前每周工作时间的总和,并将它们放入一个数组中,以便与生成条形图的图表脚本一起使用。

图表从星期一开始,到星期日结束。

我写了下面的select语句,但它返回了错误的值,如果其中一天没有记录任何小时数,也没有考虑。

有什么建议吗?

以下是代码:

$sql = "SELECT SUM(rthours) as total FROM data WHERE (WEEK(labor_date) = WEEK(NOW())) AND (user_name = '$user') GROUP BY DAY(labor_date) ORDER BY DAY(labor_date)";

$result = mysqli_query($conn, $sql);
$thours = array();

while ($row = mysqli_fetch_assoc($result)) {
           $thours[] = $row["total"];
        }
mysqli_close($conn);

?>

3 个答案:

答案 0 :(得分:1)

首先,您的代码向SQL injection开放。我不会在这里解决这个问题,但请修理它。

您需要使用函数weekday(1 - 7),而不是day(1 - 31),因为后者可能跨越一个月边界然后产生错误的顺序。

要填补空白,您可以在查询中添加一个虚拟表格,该表格将生成数字1到7,然后将数据外部加入。对于缺失的日子,您的金额仍将包括在内,但null。使用coalesce,您可以将其转换为值0:

SELECT    COALESCE(SUM(rthours), 0) as total 
FROM      (SELECT 1 as weekday
             UNION ALL SELECT 2 UNION ALL SELECT 3 
             UNION ALL SELECT 4 UNION ALL SELECT 5 
             UNION ALL SELECT 6 UNION ALL SELECT 7) as ref
LEFT JOIN data 
       ON DAYOFWEEK(labor_date) = ref.weekday
WHERE     WEEK(labor_date) = WEEK(NOW())
AND       user_name = ?
GROUP BY  ref.weekday 
ORDER BY  ref.weekday

答案 1 :(得分:0)

想出来。使用此select语句可以:

SELECT SUM(rthours) total
  FROM data 
 WHERE (WEEK(labor_date) = WEEK(NOW())) 
   AND (YEAR(labor_date) = YEAR(NOW())) 
   AND (user_name = '$user') 
 GROUP 
    BY WEEKDAY(labor_date) 
 ORDER 
    BY WEEKDAY(labor_date);

答案 2 :(得分:0)

编辑此代码:

"SELECT COALESCE(SUM(rthours) + SUM(othours) + SUM(trthours) + SUM(tothours), 0) as total
FROM (SELECT 1 as weekday
             UNION ALL SELECT 2 UNION ALL SELECT 3
             UNION ALL SELECT 4 UNION ALL SELECT 5
             UNION ALL SELECT 6 UNION ALL SELECT 7) as ref
LEFT JOIN data
       ON DAYOFWEEK(labor_date) = ref.weekday
WHERE     WEEK(labor_date) = WEEK(NOW()) AND Year(labor_date) = Year(NOW())
AND       user_name = '$user'
GROUP BY  ref.weekday
ORDER BY  ref.weekday";

代码正在抓取数据,但在某一天数据不存在时仍然没有放置零。