2011-07-29 54 views
-4

我正在使用mysql5。如何使用sql請求計算百分比

我想使用SQL請求來計算一個百分比,但我無法做到這一點。

我想計算每個環境的百分比,但我可以計算出環境的 百分比。

我寫了兩條sql語句,一條返回成功測試的結果數,另一條返回成功測試的總數。

他們每個人都能正常工作,但我無法在相同的語句中使用它們來計算百分比。

第一個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 
+4

混淆措辭,沒有完全指定的問題。無法回答。 –

回答

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

+0

,非常感謝:) – rym