我有两个包含类似数据的数据库表 - 一个是流程完成的工作量,另一个是该流程产生的错误数量。
我想显示正确的第一次工作的百分比。
我按进程计算项目数的查询是:
SELECT Counter.Process, count( Counter.Process ) AS count
FROM Counter WHERE (TIME BETWEEN '2012-07-01 00:00:00' AND '2012-07-06 23:59:59')
GROUP BY Counter.Process
ORDER BY count DESC
上面给出了一个类似于:
的列表Process | count
-------------------
Process A | 40
Process B | 32
Process C | 102
Process D | 23
我有第二个表格,其中包含相同的字段,用于记录错误,称为“错误”。
通过使用相同的查询(但显然更改了表名),我可以得到一个进程和错误列表。
我想要做的是创建一个PHP网页,显示每个进程的错误百分比。
我的问题是如果我单独创建两个查询,当我使用PHP Where循环遍历它们时我不知道如何使计算显示百分比。
我尝试在两个SQL查询之间使用UNION,但我不能让它显示针对该进程的两个不同的计数读数。
理想情况下,我想要一种显示数据的方法:
Process | Counter.count | Errors.count
Process A 40 2
Process B 32 0
Process C 102 18
Process D 23 8
我非常感谢有关如何实现这一目标的任何建议/建议 - 如果您需要有关我的数据库表的更多信息,请告诉我
感谢您阅读
取值
答案 0 :(得分:0)
我没有运行它所以可能会有错误。你可以做两个选择,然后加入结果:
select s.process, s.success_count, e.error_count
from
(SELECT Counter.Process as process, count( Counter.Process ) AS success_count
FROM Counter
WHERE (TIME BETWEEN '2012-07-01 00:00:00' AND '2012-07-06 23:59:59')
GROUP BY Counter.Process
) s left join
(SELECT Errors.Process, count( Errors.Process ) AS error_count
FROM Errors
WHERE (TIME BETWEEN '2012-07-01 00:00:00' AND '2012-07-06 23:59:59')
GROUP BY Errors.Process
) e
on (s.Process = e.process)
答案 1 :(得分:0)
我个人更喜欢通过PHP运行这样的情况,因为它让我更加困惑,所以我会解释我认为我会用PHP做什么(我说'想'因为我可能不知道你的数据库结构或系统否则会使我的规格):
$rows = array();
$res = mysql_query('SELECT Counter.Process, count( Counter.Process ) AS count
FROM Counter WHERE (TIME BETWEEN '2012-07-01 00:00:00' AND '2012-07-06 23:59:59')
GROUP BY Counter.Process
ORDER BY count DESC');
while ($arr = mysql_fetch_assoc($res))
{
$rows[] = $arr;
}
$res2 = mysql_query('SELECT Errors.Process, count( Errors.Process ) AS count
FROM Counter WHERE (TIME BETWEEN '2012-07-01 00:00:00' AND '2012-07-06 23:59:59')
GROUP BY Errors.Process
ORDER BY count DESC');
while ($arr2 = mysql_fetch_assoc($res2)
{
for ($i=0; $i<count($rows); $i++)
{
if ($arr2["Process"] == $data[$i]["process"])
{
break;
}
//Do your functions with $arr and $data[$i] at this point...
}
}
答案 2 :(得分:0)
没有子查询这样做应该很简单:
SELECT
Counter.Process
, COUNT(Counter.Process) AS ProcessCount
, COUNT(Errors.Process) AS ProcessErrors
FROM
Counter
LEFT JOIN
Errors
ON Counter.Process = Errors.Process
WHERE
Counter.TIME BETWEEN '2012-07-01 00:00:00' AND '2012-07-06 23:59:59'
GROUP BY
Counter.Process
您可以对这两个查询进行说明,看看哪种查询最适合您的数据。
-edit:我已将其更改为LEFT JOIN,因此如果进程没有错误,您不会错过任何行。
答案 3 :(得分:-1)
您可以使用子查询:
SELECT Counter.Process, count( Counter.Process ) AS Count,
(SELECT count(Errors.Process)
FROM Errors
WHERE Process=Counter.Process
AND (TIME BETWEEN '2012-07-01 00:00:00' AND '2012-07-06 23:59:59')) AS Errors
FROM Counter WHERE (TIME BETWEEN '2012-07-01 00:00:00' AND '2012-07-06 23:59:59')
GROUP BY Counter.Process
ORDER BY count DESC
此致 尼尔。