我的表中ID列是自增+1的主键。要对ID进行查询,要求是1<=ID<=14之间,每隔三行选取一行,15<=ID<=24之间,每隔两行选取一行.表:table1
ID
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
想要的查询结果如下:
1
3
6
9
12
16
18
20
22
24

解决方案 »

  1.   

    select id from tb 
    where id=(
    case when id>=1 and id<=3 then (id+2)/3*3-2
    case when id>=15 and id<=24 then (id-15)/2*2+15
    end)
      

  2.   

    qianjin036a你的代码执行时提示错误:
    消息 156,级别 15,状态 1,第 4 行
    关键字 'case' 附近有语法错误。如何改
      

  3.   

    select id from tb 
    where id in(
    case when id>=1 and id<=3 then (id+2)/3*3-2
    case when id>=15 and id<=24 then (id-15)/2*2+15
    end)
      

  4.   

    哥们:
    间隔两行取一行应该是 1,4,7,...
    select id from(
    select number+1 as id from master..spt_values where type='p' and number<24
    )t
    where id=(
    case when id>=1 and id<=14 then (id+2)/3*3-2
     when id>=15 and id<=24 then (id-14)/2*2+14
    end)
    /*
    id
    -----------
    1
    4
    7
    10
    13
    16
    18
    20
    22
    24(10 行受影响)*/
      

  5.   

    对了,既然是15至...间隔一行,那么15应该取上啊.
    select id from(
    select number+1 as id from master..spt_values where type='p' and number<24
    )t
    where id=(
    case when id>=1 and id<=14 then (id+2)/3*3-2
     when id>=15 and id<=24 then (id-15)/2*2+15
    end)
    /*
    id
    -----------
    1
    4
    7
    10
    13
    15
    17
    19
    21
    23(10 行受影响)*/