我有一个包含主要表格列createon
(date
)&的CRM数据库createat
(time
)。我们称之为表A
有一个辅助表,用于记录有关尝试联系在A中创建的记录时所采取的活动的数据,让我们调用此表B.
我正在尝试编写一个tSQL查询,它将显示在A& A中创建记录之间的平均时间。第一个活动记录在B.
这是我到目前为止所做的:
SELECT
B.userid,
avg(cast(datediff(MINUTE, A.createat, B.ontime) as float))
AS 'AVG TIME FROM LEAD CREATION TO FIRST LOGGED ACTIVITY'
FROM
TableA A, TableB B
WHERE
A.KEY_value = B.KEY_value
AND B.USERID in ('USER1','USER2','USER3','USER4','USER5')
AND B.ONDATE > '09/01/2014'
GROUP BY
B.USERID
HAVING
B.ontime = min(B.ontime)
如果我删除'having'子句,查询将会起作用,但我无法确定我是否得到了表B中第一次记录活动的时间(min(B.ontime))
我仍然是一个SQL新手所以任何帮助/指导都将非常感谢!
答案 0 :(得分:0)
要做的一种方法是为子查询中的每个用户按时间最小化,并与表A一起加入。
SELECT
T.userid,
ISNULL(avg(cast(datediff(MINUTE, cast(A.createat as datetime)+A.createdon, T.MinOnTime) as float)),0)
AS [AVG TIME FROM LEAD CREATION TO FIRST LOGGED ACTIVITY]
FROM
TableA A
LEFT JOIN ( SELECT Key_value, userid, min(cast(B.ontime as datetime) + B.ondate) as MinOnTime FROM
TableB B
WHERE B.USERID in ('USER1','USER2','USER3','USER4','USER5')
AND B.ONDATE > '09/01/2014'
GROUP BY KEY_Value, userid
) T
on A.KEY_value = T.KEY_value
GROUP BY T.userid
答案 1 :(得分:0)
SELECT
t.userid
,case when A.createon = B.ondate then avg(cast(datediff(MINUTE, A.createat, B.ontime) as float))
else avg(datediff(MINUTE, A.createon, B.ondate)+(cast(datediff(MINUTE, A.createat, B.ontime) as float)))
end as 'AVG TIME FROM LEAD CREATION TO FIRST LOGGED ACTIVITY'
FROM
TableA a
LEFT JOIN ( SELECT Key_value, userid, min(B.ontime) as MinOnTime
FROM TableB b
WHERE b.USERID in ('USER1','USER2','USER3','USER4','USER5')
and b.ondate > '2014/09/01'
GROUP BY KEY_Value, userid) t on a.KEY_value = t.KEY_value
GROUP BY
t.userid
答案 2 :(得分:0)
SELECT
B.userid,
avg(cast(datediff(MINUTE, A.createat, min(B.ontime)) as float))
AS 'AVG TIME FROM LEAD CREATION TO FIRST LOGGED ACTIVITY'
FROM
TableA A, TableB B
WHERE
A.KEY_value = B.KEY_value
AND B.USERID in ('USER1','USER2','USER3','USER4','USER5')
AND B.ONDATE > '09/01/2014'
GROUP BY
B.USERID