用单个查询计算总时间差

时间:2014-05-19 09:21:56

标签: sql-server time count group-by

我有来自数据库的数据像这样:

HDiffrence  MDiffrence          Interv
      2      14          2 Hours 14 Minutes 
      0      4           0 Hours 4 Minutes 

所以我需要将H和M都转换为时间格式,并在其他查询中做一些逻辑事务

我做这样的检查,这是检查HH:MM是否超过15分钟:

count((select(case when((select convert(time,(HDiffrence +':'+MDiffrence),114)) > ((select convert(time,('00' +':'+'15'),114))) )then 1 when ((select convert(time,(HDiffrence +':'+MDiffrence),114)) is null)  then null else 0 end)))

我将支票放入:

select contractor , COUNT(pm.PantauID) as total ,
count((select(case when((select convert(time,(HDiffrence +':'+MDiffrence),114)) > ((select convert(time,('00' +':'+'15'),114))) )then 1 when ((select convert(time,(HDiffrence +':'+MDiffrence),114)) is null)  then null else 0 end)))
   from Pantau p
left join PantauMSG pm
on p.PantauID = pm.PantauID
where PantauType = 'PT2' and PantauStatus <> 'PS1' and  
(CAST(SCH_DATE AS DATE) = (SELECT CONVERT (DATE, GETDATE(), 103) AS Expr1))
group by  CONTRACTOR 

但是,绝对会得到错误:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

所以根据我的逻辑来检查时间,是否更简化计算值超过15分钟

2 个答案:

答案 0 :(得分:1)

如果您只使用小时和分钟的整数值,只需使用基本数学而不是将其转换为时间值:

declare @hours int = 1
declare @mins int = 35
declare @total_mins int = (@hours * 60) + @mins

select @total_mins - 15

然后使用类似这样的东西:

select contractor, COUNT(pm.PantauID) as total, sum(HDiffrence) as Hours, 
       sum(MDiffrence) as Minutes, sum(HDiffrence) * 60 + sum(MDiffrence) as TotalMinutes
from Pantau p
left join PantauMSG pm
on p.PantauID = pm.PantauID
where PantauType = 'PT2' and PantauStatus <> 'PS1' and  
(CAST(SCH_DATE AS DATE) = (SELECT CONVERT (DATE, GETDATE(), 103) AS Expr1))
group by  CONTRACTOR 

答案 1 :(得分:0)

好的,基于Tanner Idea,我改变了我的查询,是的,最后它起作用了:

 select contractor , COUNT(pm.PantauID) as total ,
        count(case when ((convert(int, HDiffrence)* 60 )+convert(int,MDiffrence)) > 15 then ((convert(int, HDiffrence)* 60 )+convert(int,MDiffrence)) else null end) as Morethan15,
        count(case when ((convert(int, HDiffrence)* 60 )+convert(int,MDiffrence)) < 15 then ((convert(int, HDiffrence)* 60 )+convert(int,MDiffrence)) else null end) as lessthan15
 from Pantau p

    left join PantauMSG pm
    on p.PantauID = pm.PantauID

    where PantauType = 'PT2' and PantauStatus <> 'PS1' and  
    (CAST(SCH_DATE AS DATE) = (SELECT CONVERT (DATE, GETDATE(), 103) AS Expr1))
    group by  CONTRACTOR