2015-02-11 53 views
0

我有一个表SOW,其中有列ASSOCIATE,SOW_START_DATE,SOW_END_DATE,其中我需要获得2014年的一个月关联人数,例如我有相关联的Minal,其sow_start_date是1-01-2014,sow_end_date是1-04-2014我想查询哪里最小可用于1月,2月,3月和4月。 我已经试过这个查询,但结果是minal只可用于1月,而不是f一月,二月,三月,四月。1月14日至12月14日期间分包商的月明智人数

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

为什么在你的查询您是通过设置即二月只记录过滤月([SOW开始日期)= 2。另外,请通过在DB和Sample O/p中提供样本记录,以便输入您期望的样本确切的o/p。那么它会帮助人们快速回答你的问题 – 2015-02-11 14:04:15

+0

你需要什么? Mimal可用的月份数或实际的月份列表?样本输入和期望的输出数据将是最有帮助的。 – TomT 2015-02-11 22:54:08

+0

我想拥有employess的月度计数。 – 2015-02-18 09:57:25

回答

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 

退房小提琴http://www.sqlfiddle.com/#!3/52c94b/3/0

+0

Thanks allot,但我需要显示一个员工的所有数据。即使我尝试修改此查询,但无法这样做..请帮助我查询,以便我可以在同一个查询中添加所有相应的数据。 – 2015-03-09 10:13:37

+0

我不明白你需要什么。正如我在之前的评论中已经提到的那样,您需要使用您的示例输入数据和预期输出来更新您的问题。这应该解释它。此外,不要说你的问题是紧迫的。如果你一个月后仍然被阻塞,那显然不是。 – TomT 2015-03-09 19:23:00

相关问题