2015-02-11 83 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

相關問題