如何使用sql请求计算百分比

时间:2011-07-29 07:44:43

标签: mysql sql

我正在使用mysql5。

我想使用SQL请求计算一个百分比,但我不能这样做。

我想计算每个环境的百分比,但我可以计算一个 环境的百分比。

我写了两个sql语句,一个返回成功测试的数量,OK结果,第二个返回成功测试的总数。

它们中的每一个都运行正常,但我无法在同一语句中使用它们来计算百分比。

第一个SQL语句:

SELECT count(result.success),
       result.RESULT_ENV
FROM result, 
     scenario,
     env
WHERE result.RESULT_ENV = env.ENV_URL
AND scenario.PHASE_ID = result.RESULT_PHASE
AND scenario.PHASE_ID = "availibility"
AND result.TIME BETWEEN '2011-07-14 12:00:00' AND '2011-07-15 10:12:59' 
AND result.TIME NOT BETWEEN 
    (
        SELECT MW_DB 
        FROM mw 
        WHERE MW_DB  BETWEEN '2011-07-14 12:00:00' AND '2011-07-15 10:12:59'
    ) AND 
    (
        SELECT MW_DF 
        FROM mw 
        WHERE MW_DB BETWEEN '2011-07-14 12:00:00' AND '2011-07-15 10:00:55'
    )
AND result.SUCCESS = "ok" 
GROUP BY result.RESULT_ENV

返回:

number  |     RESULT_ENV
--------+------------------
  6     |    http://somip1
  1     |    http://somip2

第二个SQL语句:

SELECT count(result.success),
       result.RESULT_ENV
FROM result, 
     scenario,
     env
WHERE result.RESULT_ENV = env.ENV_URL
AND scenario.PHASE_ID = result.RESULT_PHASE
AND scenario.PHASE_ID = "availibility"
AND result.TIME BETWEEN '2011-07-14 12:00:00' AND '2011-07-15 10:12:59' 
AND result.TIME NOT BETWEEN 
    (
        SELECT MW_DB 
        FROM mw 
        WHERE MW_DB  BETWEEN '2011-07-14 12:00:00' AND '2011-07-15 10:12:59'
    ) AND 
    (
        SELECT MW_DF 
        FROM mw 
        WHERE MW_DB BETWEEN '2011-07-14 12:00:00' AND '2011-07-15 10:00:55'
    )
GROUP BY result.RESULT_ENV

返回:

number  |     RESULT_ENV
--------+------------------
  8     |    http://somip1
  2     |    http://somip2

结果应为:

percent |     RESULT_ENV
--------+------------------
  75    |    http://somip1
  50    |    http://somip2

1 个答案:

答案 0 :(得分:0)

您需要使用CASE statement之类的内容:

(100 * SUM(CASE WHEN result.SUCCESS = 'ok' THEN 1 ELSE 0)) / COUNT(result.success)

然后你的查询必须是这样的:

SELECT (100 * SUM(CASE WHEN result.SUCCESS = 'ok' THEN 1 ELSE 0)) / COUNT(result.success),
       result.RESULT_ENV
FROM result, 
     scenario,
     env
WHERE result.RESULT_ENV = env.ENV_URL
AND scenario.PHASE_ID = result.RESULT_PHASE
AND scenario.PHASE_ID = "availibility"
AND result.TIME BETWEEN '2011-07-14 12:00:00' AND '2011-07-15 10:12:59' 
AND result.TIME NOT BETWEEN 
    (
        SELECT MW_DB 
        FROM mw 
        WHERE MW_DB  BETWEEN '2011-07-14 12:00:00' AND '2011-07-15 10:12:59'
    ) AND 
    (
        SELECT MW_DF 
        FROM mw 
        WHERE MW_DB BETWEEN '2011-07-14 12:00:00' AND '2011-07-15 10:00:55'
    )
GROUP BY result.RESULT_ENV

See the doc