按Sum过滤而不分组

时间:2014-02-13 13:32:14

标签: sql reporting-services

我有一个结果集,我从一个看起来像这样的查询生成:

  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的员工 在上面的例子中,霍华德将被过滤掉。

有没有办法很好地做到这一点,或者只是不可能甚至变瘦?

(注:由于我将使用Reporting Services上的查询,我无法使用OVER功能)

谢谢大家的帮助

2 个答案:

答案 0 :(得分:3)

这看起来像是SQL Server语法,因此我可以使用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 :(得分:0)

尝试:

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