Postgres在内部联接声明中正确使用Group by

时间:2015-07-17 11:51:00

标签: database postgresql group-by

编辑我使用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_idagent_id是相同的。

我想根据所选日期得到结果,例如2015-07-17我得到了结果但我的问题是loginhours基于每个用户的应用数量SUM 。例如,user1forms表上有2条记录,而loginhours中的2015-07-172,那么在我的结果中,loginhours变为{ {1}}这是错误的,我认为这是在4声明中。你能帮我解决一下如何正确查询吗? 感谢

2 个答案:

答案 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