2017-10-05 112 views
0

我想要獲得分組計數的總和。在SQL查詢中分組計數

SELECT ig_idx,ig_team1,ig_team2benefit,ig_game_type 
FROM (select ig_idx,ig_team1,ig_team2benefit,ig_game_type, 
RANK() OVER(partition by ig_root,ig_game_type order by ig_idx asc) AS rank 
FROM info_game) AS t1 
WHERE rank < 2 

================================== 
idx name  odds type 
---------------------------------- 
1 Kjelsaas 1.4  dnb 
2 Kjelsaas 1.75 1x2 
3 Kjelsaas 1.75 ou 
4 Kjelsaas 1.8  ah 
5 Grorud  3  dnb 
6 Grorud  3.8  1x2 
7 Grorud  1.36 ou 
8 Grorud  2.075 ah 
9 Brumunddal 2.25 1x2 
10 Brumunddal 1.57 ou 
11 Brumunddal 2.2  ah 
================================== 

我想要一個結果。

================================== 
idx name  odds type count 
---------------------------------- 
1 Kjelsaas 1.4  dnb 4 
2 Kjelsaas 1.75 1x2 4 
3 Kjelsaas 1.75 ou  4 
4 Kjelsaas 1.8  ah  4 
5 Grorud  3  dnb 2 
6 Grorud  3.8  1x2 2 
9 Brumunddal 2.25 1x2 3 
10 Brumunddal 1.57 ou  3 
11 Brumunddal 2.2  ah  3 
================================== 
+0

第一個查詢返回您的示例數據?如果是的話,2 Grorud行發生了什麼? Grorud應該是4嗎? – SQLChao

回答

3

我假設你的查詢返回第一個表結果?你可以這樣做:

with cte_example 
as 
(SELECT ig_idx,ig_team1,ig_team2benefit,ig_game_type 
FROM (select ig_idx,ig_team1,ig_team2benefit,ig_game_type, 
RANK() OVER(partition by ig_root,ig_game_type order by ig_idx asc) AS rank 
FROM info_game) AS t1 
WHERE rank < 2) 

select * 
     ,count(name) over(partition by name) count 
from cte_example 

或者你可以在你的派生表中放入count...over函數?有很多方法可以做到這一點。或者是你的查詢嘗試和第一個表是數據樣本,使它看起來像後者?