循环使用sql表并在php中计算数字


Looping through sql table and calculate figures in php

我有一个看似简单的问题,但我无法锻炼如何做到。

Employee id | dev_time | pm_time
1           |    4     |    5
2           |    2     |    3
3           |    6     |    2
2           |    3     |    6
3           |    4     |    4
1           |    1     |    5

我在本地主机上有一个表,看起来像这样。如何计算每个员工花费的总时间(dev_time+pm_time(?我需要SQL语句和while/for/foreach循环解决方案

例如,employee_id 1总共花费了15个小时,或者employee_id 2总共花费了14个小时

谢谢!!!!!

试试这个:

  select employee_id, sum(dev_time + pm_time) as totalhours
    from mytable
group by employee_id

样本输出(DEMO(:

EMPLOYEE_ID | TOTALHOURS
1             15
2             14
3             16

I require both the SQL statement and the while/for/foreach loops solution

我有个坏消息要告诉你。我将给你一些链接,而不是直接的代码,这样你就可以自己解决这个问题。

首先,您需要了解基本的SQL运算符。然后您会发现,您想要获得所需效果的SQL语句并不是很难自己推导出来的。

其次,我会给你文本描述:

Query all tuples from the database

Loop through each one, first grabbing their dev_time value, and summing it with their pm_time value.

Store the sum value somewhere

正如Conrad Friz所提到的,这种文本描述可能会导致"N+1选择问题",这可以在一句话中完成,正如你所希望的那样。

希望您能采用这种方法,而不是简单地复制和粘贴代码。

您可以直接在SQL中执行此操作,我不确定您使用的是什么DBMS,但在MySQL中是:

SELECT *, (dev_time+pm_time) AS total FROM table_name