2013-06-22 128 views
2

我正在嘗試在Mysql的表中進行轉換。我無法弄清楚如何去做。誰能告訴我該怎麼做?輸入和輸出是給定的。我想知道它是如何完成的?Mysql查詢數據轉換

輸入表

+-------------+------------+------------------+-------------------+ 
| Employee_ID | Start_Date | Termination_Date | Performance_Level | 
+-------------+------------+------------------+-------------------+ 
|   1 | 1/1/2007 | 3/1/2007   | Low    | 
|   2 | 6/5/2004 | Null    | Medium   | 
|   3 | 4/3/2003 | Null    | High    | 
|   4 | 9/1/2002 | 4/15/2007  | Medium   | 
|   5 | 4/6/2007 | 11/1/2007  | Low    | 
|   6 | 7/1/2007 | Null    | High    | 
|   7 | 3/2/2005 | 8/1/2007   | Low    | 
+-------------+------------+------------------+-------------------+ 

輸出繼電器表

+---------+-----------------------------------+-----------------+-------------------+----------------+ 
| Period | Total_Employees_at_end_of_quarter | High_Performers | Medium_Performers | Low_Performers | 
+---------+-----------------------------------+-----------------+-------------------+----------------+ 
| Q1-2007 |         4 |    1 |     2 |    1 | 
| Q2-2007 |         4 |    1 |     1 |    2 | 
| Q3-2007 |         4 |    2 |     1 |    1 | 
| Q4-2007 |         3 |    2 |     1 |    0 | 
+---------+-----------------------------------+-----------------+-------------------+----------------+ 

這是我試過

select * from emp 
where date(sdate)< date'2007-04-01' and (date(tdate)> date'2007-03-31' or tdate is null); 

select * from emp 
where date(sdate)< date'2007-07-01' and (date(tdate)> date'2007-06-30' or tdate is null); 

select * from emp 
where date(sdate)< date'2007-010-01' and (date(tdate)> date'2007-09-30' or tdate is null); 

select * from emp 
where date(sdate)< date'2008-01-01' and (date(tdate)> date'2007-12-31' or tdate is null); 

我個人查詢,但我希望有一個單一的查詢,這將給產出。

回答

2

下面採取的方法是創建一個驅動器表中的每個季度,以及有關年度和季度信息。然後使用非Equijoin加入員工表。在季度之前或季度之前開始並在季度之後結束的員工在季度末活躍。

它使用一種技巧進行日期比較,即將年度季度組合轉換爲季度總數,方法是將年份乘以4並添加季度。這是簡化日期比較的便利方法。

select driver.qtryr, count(*) as TotalPerformers, 
     sum(Performance_level = 'High') as HighPerformers, 
     sum(Performance_level = 'Medium') as MediumPerformers, 
     sum(Performance_level = 'Low') as LowPerformers 
from (select 2007 as yr, 1 as qtr, 'Q1-2007' as qtryr union all 
     select 2007 as yr, 2 as qtr, 'Q2-2007' as qtryr union all 
     select 2007 as yr, 3 as qtr, 'Q3-2007' as qtryr union all 
     select 2007 as yr, 4 as qtr, 'Q4-2007' as qtryr 
    ) driver left outer join 
    Table1 emp 
    on year(emp.start_date)*4+quarter(emp.start_date) <= driver.yr*4+qtr and 
     (emp.termination_date is null or 
     year(emp.termination_date)*4+quarter(emp.termination_date) > driver.yr*4+qtr 
     ) 
group by driver.qtryr 
+0

謝謝。這是我需要的解決方案,今天我也學習了駕駛臺表。 – navin