答案2:在您发表评论之后。(作为旁注,您的某些日期15/1/2013
不代表13/1/2013
正确的日期格式)
select transId, sum(numberOfDays) totalQueueTime
from (
select a.transId,
datediff(day,a.addDate,isnull(r.removeDate,a.addDate)) numberOfDays
from AddTable a left join RemoveTable r on a.transId = r.transId
order by a.transId, a.addDate, r.removeDate
) X
group by transId
答案1:在您发表评论之前
假设除非将其删除,否则不会添加新记录。另请注意以下查询将带来numberOfDays as zero for unremoved records
;
select a.transId, a.addDate, r.removeDate,
datediff(day,a.addDate,isnull(r.removeDate,a.addDate)) numberOfDays
from AddTable a left join RemoveTable r on a.transId = r.transId
order by a.transId, a.addDate, r.removeDate