如何划分SQL列

时间:2019-03-11 06:48:14

标签: sql sql-server sqlcommand

我想共享SQL表列。第一列将以数据形式包含数据,最高为1-10,第二列为11-20,第三列为21-30。

enter image description here

2 个答案:

答案 0 :(得分:2)

case when expression使用条件聚合

select max(case when pagenumber<11 then pagenumber end) as "1-10",
max(case when pagenumber<21 and pagenumber>10 then pagenumber end) as "11-20",
max(case when pagenumber<31 and pagenumber>20 then pagenumber end) as "21-30"
from tablename

答案 1 :(得分:0)

我认为fa06的答案缺少必要的分组依据

select  
    max(case when (pagenumber-1)/10 = 0 then pagenumber end) as "1-10",
    max(case when (pagenumber-1)/10 = 1 then pagenumber end) as "11-20",
    max(case when (pagenumber-1)/10 = 2 then pagenumber end) as "21-30"
from t
group by (pagenumber%10)
order by 1

我在数学上进行了细分,但您也可以执行以下操作:

select  
    max(case when pagenumber between 1 and 10 then pagenumber end) as "1-10",
    max(case when pagenumber between 11 and 20 then pagenumber end) as "11-20",
    max(case when pagenumber between 21 and 30 pagenumber end) as "21-30"
from t
group by (pagenumber%10)
order by 1

group by将(例如)1、11和21放在同一行上,因为它们对mod操作都具有相同的结果:1. 2、12、22进入另一行(mod结果为2)

如果您的要求例如将1、12和23都放在同一行上,就必须使分组变得更加复杂(找到一种方法,使1、12和23在数学上都返回相同的值。例如(x%10)-((x/10)+1)