我有這個查詢計算基於日期每年的價值總和。MySQL:如何優化此QUERY?按年計算SUM(日期)
它的工作原理,但它是沉重的,需要在10K左右的記錄
運行一分鐘到2分鐘有沒有辦法來優化這一點,或者以更有效的方式寫?
"select departments sum(case when year(employment_date) = '1990' then 1 else 0 end) as '1990',"
+ "sum(case when year(employment_date) = '2010' then 1 else 0 end) as '2010',"
+ "sum(case when year(employment_date) = '2011' then 1 else 0 end) as '2011',"
+ "sum(case when year(employment_date) = '2012' then 1 else 0 end) as '2012',"
+ "sum(case when year(employment_date) = '2013' then 1 else 0 end) as '2013',"
+ "sum(case when year(employment_date) = '2014' then 1 else 0 end) as '2014',"
+ "sum(case when year(employment_date) = '2015' then 1 else 0 end) as '2015',"
+ "sum(case when year(employment_date) = '2016' then 1 else 0 end) as '2016',"
+ " count(departments.dept_id) as Total "
+ "from employees inner join departments on employees.employee_id=departments.employee_id AND departments.dept_id = ?";
sample resuts
|departments | Total | 2010 | 2011 | 2012 | 2013 | 2014 | 2015 | 2016 |
|Data systems | 100 | 30 | 10 | 5 | 15 | 20 | 12 | 8 |
|Social ssmp | 70 | 10 | 10 | 15 | 15 | 4 | 6 | 10 |
這個查詢看起來是錯誤的,就好像它的employment_date不在其中的那個年份那麼它會計入總數。 –
請提供'SHOW CREATE TABLE' –