开发者

SQL Query with computed column

开发者 https://www.devze.com 2022-12-30 08:50 出处:网络
Please help me with a query. Assume that we have a table with columns: Transaction StartTime EndTime Now, I need a query with computed column of (v开发者_开发百科alue = EndTime-Startime).

Please help me with a query. Assume that we have a table with columns:

  • Transaction
  • StartTime
  • EndTime

Now, I need a query with computed column of (v开发者_开发百科alue = EndTime-Startime). Actually I need to group Users(Transaction has a FK for Users) and sort them by average time spent for transaction.


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)


You should look into the DateDiff function. You did not specify the units of the timespan, so I assumed seconds in my solution:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消