日期:2014-05-18  浏览次数:20472 次

求查询语句!
Table :

 Id State
1 0
2 1
8 0
16 1
25 1 
56 1
... .....

10000 0

要求
A. 统计 1-15 条记录 state = 1的记录条数,16-100条记录 state = 1的记录条数

.....
9000-10000条记录 state = 1的记录条数 

B. 查询 中间50%的记录 及 ID 降充排列,前20%不要,最后30%不要



------解决方案--------------------
A. 统计 1-15 条记录 state = 1的记录条数,16-100条记录 state = 1的记录条数

.....
9000-10000条记录 state = 1的记录条数

SQL code
select sum(case when id between 1 and 15 then 1 else 0 end) [1-15],
       sum(case when id between 16 and 100 then 1 else 0 end) [16-100],
       ...自己补全
       sum(case when id between 9000 and 10000 then 1 else 0 end) [9000-1000]
from table where state = 1

------解决方案--------------------
SQL code

select sum(case when id (between 1 and 15) and state=1 then 1 else 0 end) as [1-15],
sum(case when id (between 16 and 100) and state=1 then 1 else 0 end) as [16-00]
......
from(select row_number()over(order by getdate()) as id,* from tbl)a

------解决方案--------------------
看到这个提问的时候太晚了,不知道在SQL2005中能不能用序号去解决