Home > Database > Mysql Tutorial > body text

SQLServer 分组查询相邻两条记录的时间差

WBOY
Release: 2016-06-07 15:18:41
Original
2069 people have browsed it

首先,我们通过数据库中表的两条记录来引出问题,如下图 以上为一个记录操作记录的表数据。OrderID为自增长列,后面依次为操作类型,操作时间,操作人。 现在的问题是:要求筛选出数据库中从接收到送出的时间差超过2天的全部记录。即如上图两笔单据中,红色

首先,我们通过数据库中表的两条记录来引出问题,如下图

SQLServer 分组查询相邻两条记录的时间差SQLServer 分组查询相邻两条记录的时间差

以上为一个记录操作记录的表数据。OrderID为自增长列,后面依次为操作类型,操作时间,操作人。

现在的问题是:要求筛选出数据库中从“接收”到“送出”的时间差超过2天的全部记录。即如上图两笔单据中,红色框既是要筛选出的,绿色框为正常过滤的。

为了定位相邻记录,方法为给查询语句的返回记录加个自动编号列放入临时表中,再对临时表进行操作。

SQLServer 分组查询相邻两条记录的时间差SQLServer 分组查询相邻两条记录的时间差View Code

<span>--</span><span>1.首先查出表中符合條件的所有信息</span>
<span>select</span> <span>IDENTITY</span>(<span>int</span>,<span>1</span>,<span>1</span>) <span>as</span> OIndex,<span>*</span> <span>into</span> #temp1 <span>from</span><span> 操作記錄表
</span><span>where</span> OrderID <span>in</span> (<span>select</span> OrderID <span>from</span> 單據表 <span>where</span> OrderNo <span>like</span> <span>'</span><span>APP%</span><span>'</span>) <span>order</span> <span>by</span><span> OrderID,OperateDate

</span><span>--</span><span>2.簽核時間Delay在2~7天之內</span>
<span>select</span> a.OrderID,a.OperateUser,a.OperateName <span>into</span> #temp2 <span>from</span> #temp1 a <span>inner</span> <span>join</span><span> #temp1 b 
</span><span>on</span> a.OrderID<span>=</span>b.OrderID <span>and</span> a.OperateUser<span>=</span><span>b.OperateUser
</span><span>and</span> a.OperateType<span>=</span><span>'</span><span>Receive</span><span>'</span> <span>and</span> b.OperateType<span>=</span><span>'</span><span>Send</span><span>'</span> <span>and</span> b.OIndex <span>=</span> a.OIndex<span>+</span><span>1</span>
<span>where</span> <span>datediff</span>(dd,a.operatedate,b.operatedate)<span>></span><span>2</span> <span>and</span> <span>datediff</span>(dd,a.operatedate,b.operatedate)<span><span>7</span> <span>and</span> a.operatedate<span>>=</span><span>'</span><span>2012-06-10</span><span>'</span>
<span>group</span> <span>by</span><span> a.OrderID,a.OperateUser,a.OperateName
</span><span>order</span> <span>by</span><span> a.OrderID
</span><span>--</span><span>3.異常單據和異常操作人員信息</span>
<span>select</span> <span>*</span> <span>from</span> #temp2</span>
Copy after login

可以看出,关键在分组查询后对数据的比对。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template