2016-08-02 38 views
1

的總和我有數據,看起來像這樣集團通過列A,B列值的組組合,並得到乙

+-----+-----+ 
| A | B | 
+-----+-----+ 
| 1 | a | 
| 1 | a | 
| 1 | b | 
| 1 | b | 
| 1 | c | 
| 2 | a | 
| 2 | a | 
| 2 | b | 
| 3 | b | 
| 3 | a | 
+-----+-----+ 

我需要一個查詢,會給我這樣的事情。

+-----+-----+-----+ 
| A | B | sum | 
+-----+-----+-----+ 
| 1 | a+b | 4 | 
| 1 | c+d | 1 | 
| 2 | a+b | 3 | 
| 2 | c+d | 0 | 
| 3 | a+b | 2 | 
| 3 | c+d | 0 | 
+-----+-----+-----+ 

更具體地說,在withCriteria中的grails中。我可以讓它工作,或者調整它是否是直接的mysql。我需要在哪裏按A分組,但希望第二組B是2個不同值的組合,然後是B組合的計數總和。

我見過一些使用CASE的例子但還沒有看到他們將列中的值組合在一起以獲得計數。

回答

2

這有點棘手,因爲你想顯示不存在的記錄的ID。你可以用子查詢和cross join來做到這一點。然後使用outer join回原來的表,conditional aggregation,讓您的結果:

select t.a, t.b, 
    count(case when t.b = 'a+b' and y.b in ('a','b') then 1 
     when t.b = 'c+d' and y.b in ('c','d') then 1 
     end) 
from ( 
    select distinct t.a, 
     t2.b 
    from yourtable t 
     cross join (select 'a+b' b union all select 'c+d') t2 
) t left join yourtable y on t.a = y.a 
group by t.a, t.b 
+0

對不起,反應遲緩,感謝那些工作! –