SQL查询AVG日期时间在同一表列中

时间:2015-07-08 20:08:49

标签: sql sql-server max average datediff

我正在尝试创建一个返回天数差异的查询,以获取一段时间内的平均天数。这是我需要从请求中获取状态2的最大日期和状态3的最大日期,并获取用户在该段时间内花费的时间

到目前为止,这是我现在的查询,我得到了mas和min以及日期之间的差异,但不是状态2的最大值和状态3的最大值

我到目前为止的查询:

SELECT distinct t1.user, t1.Request,
       Min(t1.Time) as MinDate, 
       Max(t1.Time) as MaxDate, 
       DATEDIFF(day, MIN(t1.Time), MAX(t1.Time))
FROM [Hst_Log]  t1
      where t1.Request = 146800
GROUP BY  t1.Request, t1.user
ORDER BY t1.user, max(t1.Time) desc

示例表:

-------------------------------
user | Request | Status | Time
-------------------------------
User 1 | 2 | 1 | 6/1/15 3:25 PM
User 2 | 1 | 1 | 2/1/15 3:24 PM
User 2 | 3 | 1 | 2/1/15 3:24 PM
User 1 | 4 | 1 | 5/10/15 3:18 PM
User 3 | 3 | 2 | 5/4/15 2:36 PM
User 2 | 2 | 2 | 6/4/15 2:34 PM
User 3 | 2 | 3 | 6/10/15 5:51 PM
User 1 | 1 | 2 | 5/1/15 5:49 PM
User 3 | 4 | 2 | 5/16/15 2:39 PM
User 2 | 4 | 2 | 5/17/15 2:32 PM
User 2 | 3 | 2 | 4/6/15 2:22 PM
User 2 | 3 | 3 | 4/7/15 2:06 PM
-------------------------------

我将感谢所有帮助

3 个答案:

答案 0 :(得分:0)

什么是SQL-Server版本?也许您可以将查询用作CTE并执行后续SELECT,您可以将最小和最大日期用作日期。

编辑:Exampel

WITH myCTE AS
(
put your query here
)
SELECT * FROM myCTE

您也可以使用myCTE进行进一步的连接,选择所需的日期,使用子选择,以及什么...和:看看OVER-link,可能会有帮助......

根据版本,您还可以考虑使用OVER https://msdn.microsoft.com/en-us/library/ms189461.aspx

答案 1 :(得分:0)

这样的事情? (MySQL的)

SELECT t.*,MAX(t.UFecha), x.*,y.*,Min(t.UFecha) as MinDate, 
       Max(t.UFecha) as MaxDate, 
       avg(x.Expr2+y.Expr3),//?????
       DATEDIFF(MIN(t.UFecha), MAX(t.UFecha)) AS Expr1 

FROM `app_upgrade_hst_log` t

left join(select count(*),Request, DATEDIFF(MIN(UFecha), MAX(UFecha)) AS Expr2 FROM `app_upgrade_hst_log` where Status=1 group by Request,Status) x on t.Request= x.Request

left join(select count(*),Request, DATEDIFF(MIN(UFecha), MAX(UFecha)) AS Expr3 FROM `app_upgrade_hst_log` where Status=2) y on t.Request= y.Request

group by t.Request,t.Status

答案 2 :(得分:0)

您需要使用子查询,因为最小和最大时间的组不同。一个查询将拉出状态为2的最小值。另一个查询将拉出状态为3的最大值。

这样的事情:

SELECT MinDt.[User], minDt.MinTime, MaxDt.MaxTime, datediff(d,minDt.MinTime, MaxDt.MaxTime) as TimeSpan
FROM

(SELECT t1.[user], t1.Request,
       Min(t1.Time) as MinTime
FROM [Hst_Log]  t1
      where t1.Request = 146800
      and t1.[status] = 2
GROUP BY  t1.Request, t1.[user]) MinDt

INNER JOIN

(SELECT t1.[user], t1.Request,
       Max(t1.Time) as MaxTime      
FROM [Hst_Log]  t1
      where t1.[status] = 3
GROUP BY  t1.Request, t1.[user]) MaxDt

ON MinDt.[User] = MaxDt.[User] and minDt.Request = maxDt.Request