2017-08-03 83 views
-2

我的數據集的第一天,一個快照看起來是這樣的:獲取有關每個月

emplid region location sub_dept dept start_dt end_dt  days 
------ ------ -------- -------- ---- -------- ---------- ---- 
123456 East NY  A   1 7/1/2005 9/30/2005 91 
123456 East NY  B   1 7/1/2012 11/9/2012 131 
123456 West San Jose C   2 7/1/2013 12/31/2013 183 
123457 East NY  B   1 7/1/2017 9/7/2017  68 
123457 East NY  B   1 7/1/2005 12/31/2005 183 
123458 East NY  B   1 7/1/2017 9/7/2017  68 
123458 West San Jose C   2 7/1/2010 7/31/2010 30 
123459 East NY  A   1 7/1/2017 9/7/2017  68 
123460 East Boston F   3 7/1/2007 11/30/2007 152 

我需要能夠得到一個快照從最小日起每月的1日每。所以在這個例子中最小日期是9/30/2005。所以我需要知道在哪一個department/sub_dept/location/region10/1/2005, 11/1/2005 , 12/1/2005每個empl通過最大日期。

+0

使用該樣本數據,預期結果是什麼? (作爲格式化文本,正確的列) – jarlh

+0

預期結果是上述所有列加上每月第一天的第1天列 –

回答

0

你沒有提到的職員表的名字,所以我把它稱爲employee_table。下面的查詢(或極爲接近)應該生成你想要什麼:

With report_limits as (
     Select Trunc(min(start_dt), 'MONTH') as min_rpt_dt, 
      Trunc(max(end_dt), 'MONTH') as max_rpt_dt 
     From employee_table), 
    report_dates as (
     Select add_months(min_rpt_dt, level-1) as rpt_dt 
     From report_limits 
    Connect By add_months(min_rpt_dt, level-1) <= max_rpt_dt) 
-- 
Select e.emplid, e.region, e.location, e.sub_dept, e.dept, 
     e.start_dt, e.end_dt, e.days, r.rpt_dt 
From report_dates r 
Inner Join employee_table e on r.rpt_dt Between e.start_dt And e.end_dt 
Order By r.rpt_dt, e.emplid; 

的report_limits查詢確定報告的日期範圍,將report_dates查詢使用CONNECT BY子句來生成一組內的日期範圍,並且主要查詢將日期列表加入員工日期。

-1

嘗試此查詢:

Declare @StartDate date='2005-09-29', 
@EndDate date='2017-04-01' 

Select *, 
Dateadd(mm, Datediff(mm, 0, date), 0) AS FirstDateOfMonth from TableName 
where date >[email protected] and date<[email protected]