使用连接或嵌套查询将3个查询合并为一个?

时间:2017-02-21 17:12:46

标签: mysql jira

我有3个不同的查询显示相同的数据,但是对于不同的日期间隔。我不确定将查询组合在一起以显示所有数据的最佳方法。我对连接或嵌套查询不是很了解,所以我不确定最好的方法。

基本上我想要4列:Associate,30 Days,60 Days和90 Days。

查询1:

SELECT cwd_user.display_name AS 'Associate', sum(worklog.timeworked/3600) AS '30 Days'
FROM worklog, cwd_user,cwd_membership
WHERE worklog.AUTHOR = cwd_user.user_name
and cwd_user.directory_id = cwd_membership.directory_id
and cwd_user.lower_user_name = cwd_membership.lower_child_name
and cwd_membership.membership_type = 'GROUP_USER'
and cwd_membership.lower_parent_name = 'atl_servicedesk_it_agents'
and worklog.STARTDATE BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)
GROUP BY cwd_user. display_name
ORDER BY cwd_user.last_name;

查询2:

SELECT cwd_user.display_name AS 'Associate', sum(worklog.timeworked/3600) AS '60 Days'
FROM worklog, cwd_user,cwd_membership
WHERE worklog.AUTHOR = cwd_user.user_name
and cwd_user.directory_id = cwd_membership.directory_id
and cwd_user.lower_user_name = cwd_membership.lower_child_name
and cwd_membership.membership_type = 'GROUP_USER'
and cwd_membership.lower_parent_name = 'atl_servicedesk_it_agents'
and worklog.STARTDATE BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 60 DAY)
GROUP BY cwd_user. display_name
ORDER BY cwd_user.last_name;

查询3:

SELECT cwd_user.display_name AS 'Associate', sum(worklog.timeworked/3600) AS '90 Days'
FROM worklog, cwd_user,cwd_membership
WHERE worklog.AUTHOR = cwd_user.user_name
and cwd_user.directory_id = cwd_membership.directory_id
and cwd_user.lower_user_name = cwd_membership.lower_child_name
and cwd_membership.membership_type = 'GROUP_USER'
and cwd_membership.lower_parent_name = 'atl_servicedesk_it_agents'
and worklog.STARTDATE BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 90 DAY)
GROUP BY cwd_user. display_name
ORDER BY cwd_user.last_name;

1 个答案:

答案 0 :(得分:0)

未经测试...因为没有什么可以测试它...

SELECT u.display_name Associate
     , SUM(CASE WHEN w.startdate BETWEEN NOW() AND NOW() + INTERVAL 30 DAY THEN w.timeworked END/3600) '30 Days'
     , SUM(CASE WHEN w.startdate BETWEEN NOW() AND NOW() + INTERVAL 60 DAY THEN w.timeworked END/3600) '60 Days'
     , SUM(CASE WHEN w.startdate BETWEEN NOW() AND NOW() + INTERVAL 90 DAY THEN w.timeworked END/3600) '90 Days'
  FROM worklog w
  JOIN cwd_user u
    ON u.user_name = w.author 
  JOIN cwd_membership m
    ON m.directory_id = u.directory_id
   AND m.lower_child_name = u.lower_user_name
 WHERE m.membership_type = 'GROUP_USER'
   AND m.lower_parent_name = 'atl_servicedesk_it_agents'
   AND w.startdate BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 90 DAY)
 GROUP 
    BY u. display_name
 ORDER 
    BY u.last_name;