2014-02-13 28 views
0

我有我的,看起來像這樣的查詢產生一個結果:過濾器由總和不進行分組

Select Employee, Month, (select case when Status = '---' then 0 Else 1 end) as PlaningValue  
    From PlanningTable PT 
    Where Month >= @From Month and Month <= @ToMonth 

這樣的結果看起來是這樣的:

|Employee| Month | PlaningValue | 
|George | 2014-01 |   1 | 
|George | 2014-02 |   1 | 
|George | 2014-03 |   0 | 
|Andrew | 2014-01 |   0 | 
|Andrew | 2014-02 |   1 | 
|Andrew | 2014-03 |   0 | 
|Howard | 2014-01 |   1 | 
|Howard | 2014-02 |   1 | 
|Howard | 2014-03 |   1 | 

現在我想要什麼是以下內容:

過濾出在上述示例中,在三個月期間內總計劃值爲3, 的員工將被過濾掉。

有沒有一種方法可以很好地完成這項工作?

(注:因爲我要使用查詢的報表服務,我不能使用OVER功能)

謝謝大家的幫助

+0

奇怪的CASE語法。爲什麼選擇它? – Alexander

回答

3

這看起來是SQL服務器語法,因爲這樣我就可以使用windowed functions

WITH CTE AS 
( SELECT Employee, 
      Month, 
      PlanningValue = CASE WHEN Status = '---' THEN 0 ELSE 1 END, 
      Total = SUM(CASE WHEN Status = '---' THEN 0 ELSE 1 END) 
         OVER (PARTITION BY Employee) 
    FROM PlanningTable 
    WHERE Month >= @FromDate 
    AND  Month <= @ToMonth 
) 
SELECT Employee, Month, PlanningValue 
FROM CTE 
WHERE Total != 3; 

Simplified Example on SQL Fiddle

+1

我認爲OP希望'WHERE Total <> 3' –

+0

@TI謝謝。我編輯了答案。 – GarethD

+0

感謝您的回答, 現在我遇到的問題是,我無法與其他查詢結合使用結果,我添加了一個分號以使上述答案在WITH之前有效,但我無法將UNION結果與另一個查詢我有,我能做些什麼? – gberisha

0

Try:

select pt.employee, pt.month, pt.planningvalue 
from planningtable pt 
    join planningtable pt2 on pt.employee = pt2.employee 
    join planningtable pt3 on pt.employee = pt3.employee 
    join planningtable pt4 on pt.employee = pt4.employee 
where month >= @mofrom and month <= @tomonth 
    and pt2.month = @tomonth 
    and pt3.month in (select month from planningtable where month > @mofrom and month < @tomonth) 
    and pt4.month = @mofrom 
    and pt2.planningvalue + pt3.planningvalue + pt4.planningvalue <> 3