2017-02-21 69 views
-1

我有3個不同的查詢顯示相同的數據,但不同的日期間隔。我不確定將查詢合併到一起顯示所有數據的最佳方式。我不擅長於連接或嵌套查詢,所以我不確定這樣做的最佳方式。將3個查詢合併爲一個,使用聯接還是嵌套查詢?

基本上我想要4列:準,30天,60天和90天。

查詢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; 
+0

請參閱http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-查詢 – Strawberry

回答

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; 
+0

這工作!你真了不起!我沒有意識到我可以這樣做,但我一定會在將來使用它! – Cole