将SQL查询中的一列拆分为多个列

时间:2015-09-29 17:22:31

标签: sql

这个想法是这样的,我有一个列的值范围从0到25,000。

我想基本上有一列可以计算0到5000,5000-10000等值的数量。

我从哪里开始?我怎么做这样的事情?

1 个答案:

答案 0 :(得分:2)

我假设你真的不希望范围重叠:

count(case when <column> between     0 and  5000 then 1 else null end) as range0,
count(case when <column> between  5001 and 10000 then 1 else null end) as range1,
...

或者你更喜欢(如果你的意思是0到4999,5000到9999等):

count(case when <column> / 5000 = 0 then 1 else null end) as range0,
count(case when <column> / 5000 = 1 then 1 else null end) as range1,
count(case when <column> / 5000 = 2 then 1 else null end) as range2,
count(case when <column> / 5000 = 3 then 1 else null end) as range3,
count(case when <column> / 5000 = 4 then 1 else null end) as range4,
count(case when <column> / 5000 = 5 then 1 else null end) as range5

你需要最后一个实际覆盖25,000或只做>= 4。请注意,我假设整数除法。