SQL Server 2008 TSQL循环并计算开始和结束时间之间的平均时间

时间:2015-10-13 11:28:32

标签: sql tsql

如何计算客户列表的开始时间和结束时间之间的平均时间

我有两张桌子

Customer         Table
Id               Id
Name             CustId
                 Start time  (datetime)
                 End time    (datetime)

包含客户列表的开始和结束时间(以分钟为单位)

如何遍历所有客户并计算开始和结束时间之间的平均时间?

所以我最终得到了结果

Name                 Average time
John Doe             13 minutes
Jane Doe              9 minutes
Frank Paco            8 minutes

开始时间和结束时间采用

数据库中的格式

2015-08-10 09:43:49.000

2015-08-10 09:47:35.000

2 个答案:

答案 0 :(得分:1)

无需循环,只需聚合:

select c.CustomerName, AvgTime
from Customer as c
join
 (
   select
      CustId,
      avg(datediff(minute, StartTime, EndTime) as AvgTime
   from tab
   group by CustId
 ) as t
on c.Id = t.CustId

如果您想将未登录更改的客户包含在LEFT JOINCOALESCE(AvgTime, 0)

答案 1 :(得分:1)

您正在寻找数据聚合(AVG函数用于多行的avarage值)。您希望每个客户有一个结果行,因此要么仅从客户中进行选择,要在子查询中获取平均时间,要么按客户加入两个表和组。

选项1:

var net = require('net');
var _ = require('lodash');

   router.post('/client', function(req, res) {
       var inputJSON = req.body;
       var HOST = '127.0.0.1';
       var PORT = 5000;
       var client = new net.Socket();
       client.connect(PORT, HOST, function() {

           console.log('CONNECTED TO: ' + HOST + ':' + PORT);
           // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
            _.forEach(inputJSON, function(value,key){
                client.write(value);
                // console.log(value);
             })

        });
    //This is the line i missed in my earlier program the client should respond
    res.send('success')
    });

选项2:

select 
  name,
  (
    select avg(datediff(minute, start_time, end_time))
    from times
    where cust_id = customer.id
  ) as avg_minutes
from customer;