从两个表中使用SQL生成报告

时间:2012-08-09 09:09:04

标签: mysql sql mysqli

我有 MySQL 制作报告的问题。主要目标是为每个用户选择所有任务,并计算每个用户的time_to_complete和time_passed的SUM之间的差异

1首先,U列出了所有DISTINCT名称

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

ISSUE1

我遇到问题,为什么它给了我这些号码? 0.1 + 0.3 = 0.4,而不是0.34545455 ...或其他

ISSUE2

我将如何将第一个选择链接到第二个选择,在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。

我需要两种解决方案

解决方案1 ​​
制作一个程序(风格模式)

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

非常感谢所有帮助!非常感谢!

1 个答案:

答案 0 :(得分: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