如何获得此查询?

时间:2012-11-26 16:45:51

标签: sql sql-server sql-server-2005

这是我的表

Create table gpscli
(
   cliente int,/*this is my id client*/
   inicio datetime,/*this is start time*/
   fin datetime,/this is finished time**/
   fecha datetime/*this is my date because inicio and fin could be a bad date*/
)

填充表就是这个

select cliente, inicio, fin, fecha from gpscli order by fecha, cliente

1 '23-04-2012 10:23:51' '23-04-2012 10:26:38' '23-04-2012 00:00:000'
2 '23-04-2012 10:28:41' '23-04-2012 10:30:12' '23-04-2012 00:00:000'
3 '23-04-2012 10:33:58' '23-04-2012 10:37:24' '23-04-2012 00:00:000'
4 '23-04-2012 10:40:42' '23-04-2012 10:43:12' '23-04-2012 00:00:000'
5 '23-04-2012 10:45:46' '23-04-2012 10:57:18' '23-04-2012 00:00:000'
1 '24-04-2012 10:23:12' '24-04-2012 10:26:28' '24-04-2012 00:00:000'
2 '24-04-2012 10:23:29' '24-04-2012 10:26:58' '24-04-2012 00:00:000'
3 '24-04-2012 10:23:23' '24-04-2012 10:26:56' '24-04-2012 00:00:000'
4 '24-04-2012 10:23:12' '24-04-2012 10:26:28' '24-04-2012 00:00:000'
5 '24-04-2012 10:23:29' '24-04-2012 10:26:58' '24-04-2012 00:00:000'
1 '24-05-2012 10:23:12' '24-05-2012 10:26:28' '24-05-2012 00:00:000'
2 '24-05-2012 10:23:29' '24-05-2012 10:26:58' '24-05-2012 00:00:000'
3 '24-05-2012 10:23:23' '24-05-2012 10:26:56' '24-05-2012 00:00:000'
4 '24-05-2012 10:23:12' '24-05-2012 10:26:28' '24-05-2012 00:00:000'
5 '24-05-2012 10:23:29' '24-05-2012 10:26:58' '24-05-2012 00:00:000'

此时用户保存此信息称为“主管”

主管是在商店问题上存储什么产品客户想要的人。

所以他(supervisores)开车了。当他打开一个窗口(在pockec pc中)时,“inicio”被保存,当主管关闭窗口时,“fin”被保存在数据库中。

现在有了这些信息,我可以通过mes了解主管给客户的时间,但我真的需要的是,主管在客户端之间移动的时间有多长。

第一个客户端在一天内没有客户端1是必需的,第一个客户端在inicio列上具有最小值。对于带有fin列的最后一个客户端也一样。

主管通过mes在客户端之间移动需要多长时间。

我需要一些东西

  • 第一个客户端转移时间为0。
  • 对于第二位客户,转移时间为inicio(此inicio列属于当前状态)- fin(此fin是前客户端)
  • 对于第三位客户,转移时间为inicio(此inicio列是最新的)- fin(此fin是前客户端)

最后我需要group by month,client

我不知道如何获得它(不使用循环,我不想使用它)

1 个答案:

答案 0 :(得分:0)

我可以解决

create table #datos
(
cliente int,
fecha datetime,
inicio datetime,
fin datetime,
id int identity
)


insert into #datos (cliente,fecha,inicio,fin)
select cliente,fecha,  isnull(t_inicio,'01/01/1900') inicio,isnull(t_fin,'01/01/1900') fin
from gpscli order by  fecha, t_inicio,t_fin


alter table #datos
add idmas1 int

update #datos set idmas1=id+1


select d.cliente, d.fecha, d.inicio, d.fin,d.id,d2.fin fin_anterior from #datos d
inner join #datos d2 on
d.id=d2.idmas1

现在我将完成的时间称为“fin_anterior”,现在我可以按客户,月份或如何进行分组