获取日期时差的存储过程

时间:2013-07-18 09:45:28

标签: sql-server tsql

Location_table:

Locid   Locname
--------------
8       Blooimng dale

LocVtypeAssign_tbl:

locid       vtid
----------- -----------
8           7
8           8

Transaction_tbl:

transactID   Locid   vtid  dtime                       Paydate
---------    -----   ----  -----------------------     ----------------------    
7497         8       7     2013-06-28 14:39:34.000     2013-06-28 18:28:20.000
7500         8       8     2013-06-28 14:41:57.000     NULL

如果我通过Locid 8,我怎么能得到vtid 7和vtid 8的日期差的总和。我使用这个公式找到日期差异:

sum(DATEDIFF(hour,t.Paydate,t.DelDate))

预期产出:

location        datediff of 7       datediff of 8
Blooming Dale   2206:30321:73242    235:3373:56915

有没有办法编写存储过程来获取此输出?

我尝试了这样的查询:

SELECT convert(varchar(10),sum(DATEDIFF(hour,t.Paydate,t.DelDate)))+':' 
      +convert(varchar(10),sum(DATEDIFF(minute,t.Paydate,t.DelDate)% 60)) + ':' 
      +convert(varchar(10),sum(DATEDIFF(SECOND,t.Paydate,t.DelDate)% 60)) 
       AS ' HH:MM:SS'
FROM Transaction_tbl t 
WHERE t.Locid=8 group by vtid

我得到这样的输出:

HH:MM:SS
----------------
2206:30321:73242
235:3373:56915

1 个答案:

答案 0 :(得分:0)

您可以尝试以下内容:

SELECT l.Locname AS location,
  convert(varchar(10),sum(DATEDIFF(hour,t7.Paydate,t7.DelDate)))+':' 
  + convert(varchar(10),sum(DATEDIFF(minute,t7.Paydate,t7.DelDate)% 60)) + ':' 
  + convert(varchar(10),sum(DATEDIFF(SECOND,t7.Paydate,t7.DelDate)% 60)) 
  AS 'datediff of 7',
  convert(varchar(10),sum(DATEDIFF(hour,t8.Paydate,t8.DelDate)))+':' 
  + convert(varchar(10),sum(DATEDIFF(minute,t8.Paydate,t8.DelDate)% 60)) + ':' 
  + convert(varchar(10),sum(DATEDIFF(SECOND,t8.Paydate,t8.DelDate)% 60)) 
  AS 'datediff of 8'
FROM Location_tbl l
JOIN Transaction_tbl t7
ON t7.locid = l.locid AND t7.vtid = 7
JOIN Transaction_tbl t8
ON t8.locid = l.locid AND t8.vtid = 8
WHERE l.Locid = 8

将其推广到另一组日期偏移量是留给读者的练习。您还可以查看PIVOT