统计一表中,某列的值在某个区间中行的个数
select sum(case
when a.value1<30 then 1 else 0 end
),
sum(case
when a.value1>30
and a.value1<70
then 1 else 0 end
),
sum(case
when a.value1>70
and a.value1<130
then 1 else 0 end
),
sum(case
when a.value1>130
then 1 else 0 end
)
from a
我们平常的思路是,只要是统计行,那么就是count了再加上嵌套,但此sql的巧妙之处就在于,他用了sum,而非count,而是sum的一个灵活运用。
可见,聚合函数与case的结合,有时其效果可取代嵌套。