编辑我使用SQL小提示示例http://sqlfiddle.com/#!15/8d88b/1更新了我的问题
我目前正在从数据库记录中进行报告,但我不知道我的查询应该是什么样子,首先我有2个表。申请表格和每个用户的登录时间表
forms
->id
->agent_id
->SomeInfo
->created_at
loginhours
->id
->user_id
->loginhours (decimal)
->created_at
我有以下列报告
UserID, TotalLoginHours, TotalApplication, Application Per Hour (aph), Revenue Per Hour (rph)
所以我现在有了这个查询
SELECT a.agent_id, SUM(b.loginhours) as TotalLoginHours, COUNT(a.id) as TotalApplication, SUM(b.loginhours) / COUNT(a.id) as ApplicationPerHour, (SUM(b.loginhours) / COUNT(a.id)) * 1.75 as RPH
FROM forms a
INNER JOIN loginhours b ON a.agent_id = b.user_id WHERE a.created_at = '2015-07-17'
GROUP BY a.agent_id
请注意,user_id
和agent_id
是相同的。
我想根据所选日期得到结果,例如2015-07-17
我得到了结果但我的问题是loginhours
基于每个用户的应用数量SUM
。例如,user1
在forms
表上有2条记录,而loginhours
中的2015-07-17
为2
,那么在我的结果中,loginhours
变为{ {1}}这是错误的,我认为这是在4
声明中。你能帮我解决一下如何正确查询吗?
感谢
答案 0 :(得分:0)
我不知道这是不是一个好习惯,但不知怎的,我用
来解决这个问题SELECT a.agent_id
,(SELECT SUM(loginhours)
FROM loginhours
WHERE user_id = a.agent_id
AND created_at = '2015-07-17'
GROUP BY created_at) as TotalLoginHours
,COUNT(a.id) as TotalApplication
,(SELECT SUM(loginhours)
FROM loginhours
WHERE user_id = a.agent_id
AND created_at = '2015-07-17'
GROUP BY created_at) / COUNT(a.id) as ApplicationPerHour
,((SELECT SUM(loginhours)
FROM loginhours
WHERE user_id = a.agent_id
AND created_at = '2015-07-17'
GROUP BY created_at) / COUNT(a.id)) * 1.75 as RPH
FROM forms a
INNER JOIN loginhours b
ON a.agent_id = b.user_id
WHERE a.created_at = '2015-07-17'
GROUP BY a.agent_id;
答案 1 :(得分:0)
SELECT user_id, loginhours, applications,
loginhours/applications as applications_per_hour,
loginhours/applications * 1.75 as rph
FROM
(
SELECT user_id, SUM(loginhours) as loginhours
FROM loginhours
WHERE created_at = '2015-07-17'
GROUP BY user_id
)hours
JOIN
(
SELECT agent_id, COUNT(DISTINCT id) as applications
FROM forms
WHERE created_at = '2015-07-17'
GROUP BY agent_id
)applications
ON hours.user_id = applications.agent_id