1

我对MySQL生成报告有疑问。主要目标是选择每个用户的所有任务,并计算每个用户的 time_to_complete 和 time_passed 的总和之间的差异

1 首先你列出了所有不同的名字

SELECT DISTINCT 
initial
FROM atm_name_initials

结果在这里=> http://sqlfiddle.com/#!2/f6cbe/1

2 其次,对于我在 atm_name_initials 中找到的每个名称,我必须执行此查询,获取有关该用户的信息

SELECT
task_given_to,
SUM(time_to_complete) AS sum_time_to_complete,
SUM(time_passed) AS sum_time_passed,
SUM(time_to_complete) - SUM(time_passed) AS sum_differance
FROM atm_tasks_dit
WHERE 
completed_percent = 100 AND
task_given_to = 'OS'

结果在这里=> http://sqlfiddle.com/#!2/f6cbe/2

问题1

我很难理解为什么它给了我这些数字?0.1 + 0.3 = 0.4,而不是 0.34545455 ... 或其他

问题2

我如何将第一个选择链接到第二个,在 PHP 中会是这样的

$result = mysql_query("
SELECT DISTINCT 
initial
FROM atm_name_initials
;") or die("An unexpected error has occur!");

while($row = mysql_fetch_assoc($result))
{
    $NameInitial = $row['initial'];

    $result2 = mysql_query("
    SELECT
    task_given_to,
    SUM(time_to_complete) AS sum_time_to_complete,
    SUM(time_passed) AS sum_time_passed,
    SUM(time_to_complete) - SUM(time_passed) AS sum_differance
    FROM atm_tasks_dit
    WHERE 
    completed_percent = 100 AND
    task_given_to = '".$NameInitial."'
    ;") or die("An unexpected error has occur!");

    while($row2 = mysql_fetch_assoc($result2))
    {
        echo $row['task_given_to']."<br/>";
        echo $row['sum_time_to_complete']."<br/>";
        echo $row['sum_time_passed']."<br/>";
        echo $row['sum_differance']."<br/>";
    }
}

但是请不要再使用 PHP,我想真正学习 SQL。

我需要两种解决方案

SOLUTION 1
制作程序(风格模式)

解决方案 2
在一个单独的查询中 SELECT 在另一个 SELECT 或其他什么中,但没有过程

所有帮助将不胜感激,非常感谢!

4

1 回答 1

2

您可以很容易地组合这两个语句:

select task_given_to,
       sum(time_to_complete) as sum_time_to_complete,
       sum(time_passed) as sum_time_passed,
       sum(time_to_complete) - sum(time_passed) as sum_differance
from atm_tasks_dit
where completed_percent = 100
and   task_given_to in (select initial 
                        from atm_name_initials)
group by task_given_to

关于问题 1:这就是浮点运算在计算机中的工作方式。如果您需要精确的数字,您将需要使用numeric.

请参阅 SQLFiddle:http ://sqlfiddle.com/#!2/ba3b9/8

于 2012-08-09T10:01:06.557 回答