在SQL Server中使用sum with order by子句

时间:2016-12-31 11:05:32

标签: sql sql-server group-by sum sql-order-by

我希望按照培训师的数据查看前3个月(即90天)的最长工作时间。我创建了一个存储过程来查看前3个月的小时数,现在我只想添加group by子句(group by trainer

这是我的存储过程,请告诉我需要做的更改

begin      
declare @h int      
declare @m int      
declare @tm int      
declare @min int      
declare @count int  
declare @d varchar(30)
declare @dt datetime
declare @d1 varchar(30)
declare @dt2 datetime

declare @dt1 datetime

set @dt = (select convert(datetime, (dateadd(day, -90, getdate())), 105))
set @d = (select convert(varchar, @dt, 105))

set @dt1 = (select convert(datetime, getdate(), 105))
set @d1 = (select convert(varchar, @dt1, 105))
set @dt2 = (select convert(datetime, @d1, 105))

set @h = (SELECT SUM(DATEPART(hh, (convert(datetime, hrs, 1))))       
          FROM sonvininsert 
          WHERE date BETWEEN convert(datetime, @d, 105) AND convert(datetime, @d1, 105)      
            AND instructore = 'primary' 
            AND status = '0' 
          GROUP BY trainer)      

set @tm = (SELECT SUM(DATEPART(mi, (convert(datetime, hrs, 1))))       
           FROM sonvininsert 
           WHERE date BETWEEN convert(datetime, @d, 105) AND convert(datetime, @d1, 105)      
             AND instructore = 'primary'   
             AND status = '0' 
           GROUP BY trainer)      

set @m = @tm / 60      
set @min = @tm % 60      
set @h = @h + @m      

select @h as hour
end 

发生以下错误:

  

Msg 512,Level 16,State 1,Line 25
  子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

     

Msg 512,Level 16,State 1,Line 30
  子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

我希望我的查询像

group by trainer 
order by trainer desc

2 个答案:

答案 0 :(得分:0)

子查询中的

$("#mCSB_2").animate({ scrollTop: $('#mCSB_2_container').prop("scrollHeight")}, 1000); 是出错的原因。子查询将查找每个培训师的总和,但您要分配给变量。

以下是为所有..group by trainer

执行此操作的一种方法
trainers

答案 1 :(得分:0)

尝试类似......

;WITH cte
     AS (SELECT trainer,
                Sum(Datepart(hh, ( CONVERT(DATETIME, hrs, 1) ))) AS H,
                Sum(Datepart(mi, ( CONVERT(DATETIME, hrs, 1) ))) AS tm
         FROM   sonvininsert
         WHERE  date BETWEEN CONVERT(DATETIME, @d, 105) AND CONVERT(DATETIME, @d1, 105)
                AND instructore = 'primary'
                AND status = '0'
         GROUP  BY trainer)
SELECT trainer,
       m = tm / 60,
       [min] = tm % 60,
       [hour] = h + m
FROM   cte 
ORDER BY trainer desc