日期:2014-05-17  浏览次数:20540 次

急!急!sql存储过程
一张表里面有CYSJ(出院时间)这个字段,select语句怎样算出这张表在CYSJ之前的数据有多少条啊

------解决方案--------------------

select count(*) from 表 where CYSJ<'时间'

------解决方案--------------------
select count(*) from tb where cysj<=''
?
------解决方案--------------------

create table #t1(a varchar(5), b varchar(5),CYSJ datetime) 
insert into #t1 select '11', '21','2012/01/01 00:00:00' 
union all select '12', '22','2012/10/10 00:00:00' 
union all select '13','23','2013/01/01 00:00:00'
union all select '13','23','2010/01/01 00:00:00'
union all select '13','23','2009/01/01 00:00:00'
 select * from #t1
 
select a.CYSJ ,ab.總數
from #t1 as a
cross apply (select COUNT(*) as 總數,max(b.CYSJ) as CYSJ from #t1  b 
where  b.CYSJ <=a.CYSJ ) ab

where a.CYSJ =ab.CYSJ  

drop table #t1

------解决方案--------------------

create table t1(a varchar(5), b varchar(5),CYSJ datetime) 

insert into t1 select '11', '21','2012/01/01 00:00:00' 
union all select '12', '22','2012/10/10 00:00:00' 
union all select '13','23','2013/01/01 00:00:00'
union all select '13','23','2010/01/01 00:00:00'
union all select '13','23','2009/01/01 00:00:00'
go

select a.CYSJ ,
       count(ab.CYSJ) '小于cysj的数据条数'
from t1 a
inner join t1 ab
        on a.CYSJ < ab.CYSJ
group by a.CYSJ
/*
CYSJ 小于cysj的数据条数
2009-01-01 00:00:00.000 4
2010-01-01 00:00:00.000 3
2012-01-01 00:00:00.000 2
2012-10-10 00:00:00.000 1
*/ 

drop table t1