2016-03-05 82 views
1

我想象我怎麼能解決我的任務:使用GROUP BY與條件,如何?

SELECT row, val1, val2, SUM(1) AS total 
FROM mess 
if(row < 0){ GROUP BY val1, val2 } if(row > 0) {GROUP BY val1} 

我需要一個選擇使用兩種不同的GROUP BY,是possable?

+1

請添加示例數據和預期輸出 –

回答

1
SELECT row, val1, val2, SUM(1) AS total, 
    CASE WHEN row<0 THEN val2 ELSE 0 END as group2 
FROM mess 
GROUP BY val1, group2 

如果行> 0的所有值將是相同的,所以組的結果將計算VAL1只

0

試試這個:

SELECT row, val1, val2, SUM(1) AS total 
FROM mess 
GROUP BY if(row>=0,val1,val1+','+val2)