我有一个表SOW,其中包含ASSOCIATE,SOW_START_DATE,SOW_END_DATE列,其中我需要获取2014年一个月的关联计数,例如我有关联的Minal,其sow_start_date是1-01-2014和sow_end_date是1-04-2014我想查询哪个minal可用于1月,2月,3月和4月。 我已经尝试过这个查询,但结果是minal仅适用于1月而不是1月,2月,3月,4月。
select year([SOW Start Date]) as [year], month([SOW Start Date]) as [months], Associate
from SOW
where month([SOW Start Date]) in (MONTH([SOW Start Date]), MONTH([SOW End Date]))
and month([SOW Start Date]) =2 and YEAR([SOW Start Date])=2014
group by year([SOW Start Date]), month([SOW Start Date]),Associate
having count(*) >= 1
order by month([SOW Start Date])
答案 0 :(得分:0)
我知道您希望列出每月的员工数量。问题是你需要将你的母猪表加入一些月份列表。我猜你没有,所以你需要制造它。您需要根据开始/结束日期将您的母猪表加入月份列表。这样,如果员工在那个月工作,您将获得一个月 - 员工对。最后,您按月分组并统计员工:
-- identify the date range
declare @min date, @max date
select @min=min(sow_start_date), @max=max(sow_end_date) from sow
-- we will identify the month by its first day
declare @start date
select @start=DATEADD(month, DATEDIFF(month, 0, @min), 0)
-- generate all months in the min-max range
; with months as
(
select @start as d
union all
select dateadd(mm, 1, d) as d from months where d < @max
)
-- move start dates to 1st day of month so the comparisson works
, sow2 as
(
select associate, sow_end_date,
DATEADD(month, DATEDIFF(month, 0, sow_start_date), 0) as sow_start_date
from sow
)
-- link employees to months
, employee_month as
(
select d, Associate from sow2 inner join months
on d >= sow_start_date and d < sow_end_date
)
-- count employees per month
select d, count(Associate) a from employee_month group by d