-2

位置表:

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
4

1 回答 1

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

将其推广到一组不同的 datediff 偏移量留给读者作为练习。您还可以查看PIVOT

于 2013-07-18T12:59:50.397 回答