使用GROUP BY有条件,怎么样?

时间:2016-03-05 07:33:47

标签: mysql sql

我想我可以如何解决我的任务:

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

我需要在一个SELECT中使用两个不同的GROUP BY,它是否可能?

2 个答案:

答案 0 :(得分: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

如果row&gt; 0,则所有值都相同,因此group result将仅计算val1

答案 1 :(得分:0)

试试这个:

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