Sql 如何获取此查询?

Sql 如何获取此查询?,sql,sql-server,sql-server-2005,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*/ ) 这张桌子是这样的 selec

这是我的桌子

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'
此信息由用户保存,此时将被称为主管

主管是一个去商店问客户想要什么产品的人

所以他在车里监督搬家。当他在pockec pc中打开一个窗口时,inicio被保存,当主管关闭窗口时,fin被保存在数据库中

现在,有了这些信息,我可以得到主管通过mes与客户相处的时间,但我真正需要的是,主管通过mes在客户之间移动需要多长时间

不需要客户端1一天内的第一个客户端,第一个客户端是inicio列上的min。对于最后一个具有fin列的客户端也是如此

mes主管在客户之间移动所用的时间

我需要像它一样的东西

对于第一个客户端,传输时间为0。 对于第二个客户端,传输时间为inicio此inicio列为当前fin此fin为前一个客户端 对于第三个客户端,传输时间为inicio此inicio列为当前fin此fin为前一个客户端 最后,我需要按月分组,客户

我不知道如何在不使用循环的情况下获得它,我不想使用它

我可以解决

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_Previor,现在我可以按客户、月份或必要的方式分组

在我们帮助您之前,您需要自己尝试一下。将列命名为“date”fecha真的很糟糕-很明显,它是一个“日期”,除了它是一个时间戳,所以…-它应该代表什么?不过,您是对的,在SQL中使用循环通常是不受欢迎的。我们还希望您能提供一些示例输出,说明您希望该示例数据如何显示,以配合您迄今为止的尝试。假设没有重叠的时间戳,这并不太糟糕,特别是当您可以访问OLAP函数的必要特性时,尽管CTE在这方面很好。