带有计算列的SQL查询

时间:2010-05-17 19:32:01

标签: sql tsql

请帮我查询一下。假设我们有一个包含列的表:

  • 交易
  • StartTime
  • 结束时间

现在,我需要一个带有计算列的查询(value = EndTime-Startime)。 实际上我需要对用户进行分组(交易有用户的FK)并按平均交易时间对它们进行排序。

2 个答案:

答案 0 :(得分:5)

SELECT u.userid
       ,AVG(DATEDIFF(second, StartTime, EndTime) AS AvgTime
FROM trxn AS t
INNER JOIN users AS u
    ON trxn.userid = u.userid
GROUP BY u.userid
ORDER BY AVG(DATEDIFF(second, StartTime, EndTime)

答案 1 :(得分:3)

您应该查看DateDiff函数。你没有指定时间跨度的单位,所以我在我的解决方案中假设秒数:

Select ...
From dbo.Users As U
    Join    (
            Select T.UserId, Avg( DateDiff(s, T.StartTime, T.EndTime) ) As AvgTimespan
            From dbo.Transactions As T
            Group By T.UserId
            ) As Z
        On Z.UserId = U.Id
Order By Z.Timespan Desc