我的数据集如下所示:
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/region
每个10/1/2005, 11/1/2005 , 12/1/2005
在uber-jar
一直到最大日期。
答案 0 :(得分: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 :(得分:-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 >=@StartDate and date<=@EndDate