优化MySQl查询(从列级查询中替换)

时间:2014-01-20 12:03:27

标签: mysql-workbench

我有以下MySQL查询。如何优化它。

基本上这个查询正在做什么。
我有两个不同的员工表和他的工资表,我需要显示每个员工和每个月的国家保险费的总和作为列。
我能够实现这一功能,但我认为这种方法是正确的。
如何根据性能修改此声明。

DECLARE firstStartDate DATETIME;
SET firstStartDate = GetFirstPeriodStartDateForFiscalYear(iGroupID,iFiscalYear);
SELECT
(SELECT fullname) as 'Employee Name',

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(firstStartDate)=MONTHNAME(PeriodEndDate)) as 'Mon1',  

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 1 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon2' ,

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 2 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon3' ,

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 3 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon4' ,

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 4 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon5' ,

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 5 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon6' ,

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 6 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon7' ,

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 7 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon8' ,

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 8 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon9' ,

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 9 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon10' ,

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 10 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon11' ,

(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 11 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon12' 

FROM  Employee
LEFT OUTER JOIN eepayhistory
    ON eepayhistory.employee_id = Employee.pkEmpid
    AND Employee.CompanyId = iCompanyID


Group by 'Employee Name';

如何优化此查询。

0 个答案:

没有答案