下面的查询除响应时间外运行良好,需要4秒钟来获取记录,我需要知道最佳实践技巧来编写记录,因此查询执行时间将得到改善。
SELECT name,loc_id,tot_emp,net_salary,gross_earn,gross_deduct,case WHEN YEAR_MONTH IS NOT NULL THEN YEAR_MONTH ELSE 'NA' END AS Month
FROM
--SELECT * FROM
(SELECT
r.NAME,
'000' loc_id,
COUNT(DISTINCT ess.employee_id) tot_emp,
SUM(CASE WHEN ess.employee_id IS NOT NULL Then ess.net_salary else 0 end) net_salary,
SUM(CASE WHEN ess.employee_id IS NOT NULL Then ess.gross_earning else 0 end) gross_earn,
SUM(CASE WHEN ess.employee_id IS NOT NULL Then ess.gross_deduction else 0 end) gross_deduct,
MAX(ess.YEAR_MONTH)YEAR_MONTH
FROM Region r
JOIN EMPLOYEE e
ON r.REGION_ID=e.REGION_ID
LEFT JOIN EMPLOYEE_SALARY_SUMMARY ess
ON ess.EMPLOYEE_ID=e.EMP_ID
WHERE e.CIRCLE_ID IS NULL
group by r.NAME, '000'
UNION
SELECT
c.name,
c.circle_id loc_id,
COUNT(DISTINCT ess.employee_id) tot_emp,
SUM(CASE WHEN ess.employee_id IS NOT NULL Then ess.net_salary else 0 end) net_salary,
SUM(CASE WHEN ess.employee_id IS NOT NULL Then ess.gross_earning else 0 end) gross_earn,
SUM(CASE WHEN ess.employee_id IS NOT NULL Then ess.gross_deduction else 0 end) gross_deduct,
MAX(ess.YEAR_MONTH)YEAR_MONTH
FROM circle c
JOIN EMPLOYEE e
ON c.CIRCLE_ID=e.CIRCLE_ID
LEFT JOIN EMPLOYEE_SALARY_SUMMARY ess
ON ess.EMPLOYEE_ID=e.EMP_ID
group by c.name, c.circle_id
)mtybl
ORDER BY loc_id;
答案 0 :(得分:0)
您可以用联接替换工会,我在上面的查询中做了一些更改,用您的数据对其进行了测试。我通过从您的查询中引用来使用左联接,但是尝试使用内部联接以获得更好的性能。
SELECT name,loc_id,tot_emp,net_salary,gross_earn,gross_deduct,YEAR_MONTH
--SELECT * FROM
(
SELECT
r.NAME,
CASE WHEN C.CIRCLE_ID IS NULL THEN '000' ELSE c.circle_id END loc_id,
COUNT(DISTINCT ess.employee_id) tot_emp,
SUM(CASE WHEN ess.employee_id IS NOT NULL Then ess.net_salary else 0 end) net_salary,
SUM(CASE WHEN ess.employee_id IS NOT NULL Then ess.gross_earning else 0 end) gross_earn,
SUM(CASE WHEN ess.employee_id IS NOT NULL Then ess.gross_deduction else 0 end) gross_deduct,
CASE WHEN MAX(ess.YEAR_MONTH) IS NULL THEN 'NA' ELSE MAX(ess.YEAR_MONTH) END YEAR_MONTH
FROM EMPLOYEE e Region
JOIN EMPLOYEE_SALARY_SUMMARY ess
ON ess.EMPLOYEE_ID = e.EMP_ID
LEFT JOIN Region r
ON r.REGION_ID=e.REGION_ID
LEFT JOIN circle c
ON c.CIRCLE_ID = e.CIRCLE_ID
group by r.NAME, '000', c.circle_id
)mtybl
ORDER BY loc_id;