请教一条sql语句如何写
我有以下表结构
id status time
1 a 2010-2-21 08:13:23
2 b 2010-2-21 08:15:10
3 a 2010-2-21 08:19:29
4 b 2010-2-21 09:13:30
5 a 2010-2-21 10:13:49
我想得到以下结果,以id 升序来处理,最早一个status为b和a的time时间差,秒为单位,即id=2和id=1的那两条记录,然后如此类推再加上下一个status:b和a 的time时间差(秒为单位),直到最后一个status=a的记录的时候,如果没有下一条status为b的time作参考计算时间差,那么直接取当前服务器时间来获得时间差,最后获得时间差的总和,那么如何使用一条sql语句获得此结果?
SQL code:
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[status] varchar(1),[time] datetime)
insert [tb]
select 1,'a','2010-2-21 08:13:23' union all
select 2,'b','2010-2-21 08:15:10' union all
select 3,'a','2010-2-21 08:19:29' union all
select 4,'b','2010-2-21 09:13:30' union all
select 5,'a','2010-2-21 10:13:49'
---查询---
select
sum(datediff(ss,a.[time],isnull(b.[time],getdate()))) as [时间差总和(秒)]
from
(select *,px=(select count(1) from tb where status='a' and [time]<t.[time]) from tb t where status='a') a
left join
(select *,px=(select count(1) from tb where status='b' and [time]<
相关问答:
可能因为工作的原因 接触数据库这块比较少,之前都是做程序这块,数据库这块都有专门的人来做 分工都很明细 所以对数据库这一块完全不了解。前段时间 去面试了几家公司 几乎都是在数据库这块挂掉的 连个简单的SQ ......
现在有两张表:文章主表A(articleId,articleTitle),文章评论表B(commentId,articleId,commentTitle)
现在我想实现这样的功能:列出文章列表,其中每篇文章标题下面列出此文章的前2个文章评论,请问sql语句怎么写啊 ......
如何在SQL2005中设定定时作业,比如说定时清理某些表的数据,
或者是定时的将某些表的数据导出excel!
在线等待,急急急,最好是详细步骤!
之前我做的作业有点问题!
帮UP
参考:http://hi.baidu.com/toiota ......
关于SQL Server Mobile Edition
用Microsoft SQL Server2005 Management Studio Express9.00.3042.00创建SQLCE数据库sqlmobile.sdf
在mobile系统终端上用SQL Server Mobile Edition3.0能查看sqlmobile.sdf里表数据 ......