2016-02-24 104 views
0
+------------+---------+------------+--------------+------+ 
| dt   | status | code  | arena  | cnt | 
+------------+---------+------------+--------------+------+ 
| 2016-01-01 | failure | AB   | kingdom1  | 2 | 
| 2016-01-01 | success | AB   | kingdom1  | 16 | 
| 2016-01-01 | failure | CD   | kingdom1  | 50 | 
| 2016-01-01 | success | CD   | kingdom1  | 662 | 
| 2016-01-01 | failure | EF   | kingdom1  | 131 | 
| 2016-01-01 | success | EF   | kingdom1  | 622 | 

SQL查詢:獲取失敗百分比列

select DATE(created) as dt, status, code, arena,count(status) as cnt 
from game_table 
where some_condition 
group by dt, code, status) 

要求:

我需要找到codearena明智的不良率,但我試圖將返回100全部失敗(baaaaad編碼器)。

+------------+---------+------------+--------------+------+ 
| dt   | status | code  | arena  |failed| 
+------------+---------+------------+--------------+------+ 
| 2016-01-01 | failure | AB   | kingdom1  | 11.1 | 
| 2016-01-01 | failure | CD   | kingdom1  | 7.02 | 
| 2016-01-01 | failure | EF   | kingdom1  | 17.4 | 

我想:

select dt, cnt/sum(cnt) as p, status, code, arena 
from (
    select DATE(created) as dt, status, code, arena,count(status) as cnt 
    from game_table 
    where some_condition 
    group by dt, code, status 
) as inner_t 
group by dt, code, status; 
+0

請顯示您的預期結果行。 –

+0

@ThorstenKettner:新增 – NoobEditor

+0

好。代碼GH不在結果中。王國2也不是。這是故意的嗎?如果是這樣,他們沒有被選中的共鳴是什麼?代碼AB應該有2/18 * 100 = 11.1的報價,對吧? –

回答

1

主要的問題似乎是正確理解GROUP BY。它只意味着「每______向我顯示一個結果行」。你想要一個結果行,每code看來,所以你group by code。如果你想要一行codearena,你需要group by code, arena。對於不在GROUP BY中的字段,決定顯示哪個聚集,例如最低日期。

select 
    min(created) 
    'failure' as status, 
    code, 
    min(arena) as arena, 
    count(case when status = 'failure' then 1 end)/count(*) * 100 as failed 
from game_table 
where some_condition 
group by code; 
1

您可以通過代碼獲取失敗或成功組的百分比如下圖所示。

select DATE(created) as dt, count(case when status = "failure" then 1 end) * 100/count(status) as failure, code, arena, cnt 
from percent_issue group by code 
+0

他複製我的答案時,他是如何得到upvote的? – sagi

+0

@amit:-1,你檢查了你的查詢哪裏有'dt'? – NoobEditor

+1

對不起dt應該用「DATE(created)as dt」替換, 我的查詢和上面的查詢有區別。 –