2010-05-17 157 views
0

請幫我查詢。假設我們有列的表格:SQL查詢計算列

  • 交易
  • 開始時間
  • 結束時間

現在,我需要的計算列(值=結束時間 - STARTIME)查詢。 其實我需要將用戶分組(交易有用戶的FK),並按平均花費時間進行排序。

回答

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 
+0

我不知道它是否容易變形爲LINQ查詢? – Agzam 2010-05-17 20:55:58

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)