2

我有一个表定义和填充如下:

DECLARE @Temp TABLE
(
    ProjectId INT,
    EmployeeId INT,
    SomeTypeId INT,
    IsExpired BIT,
    IsWarning BIT,
    IsIncomplete BIT
)

--all incomplete...
INSERT INTO @Temp VALUES (1, 1, 1, 0, 0, 1)
INSERT INTO @Temp VALUES (1, 1, 2, 0, 0, 1)
INSERT INTO @Temp VALUES (1, 1, 3, 0, 0, 1)

--two warnings...
INSERT INTO @Temp VALUES (1, 2, 1, 0, 1, 0)
INSERT INTO @Temp VALUES (1, 2, 2, 0, 1, 0)
INSERT INTO @Temp VALUES (1, 2, 3, 0, 0, 0)

--two expirations...
INSERT INTO @Temp VALUES (1, 3, 1, 0, 0, 0)
INSERT INTO @Temp VALUES (1, 3, 2, 1, 0, 0)
INSERT INTO @Temp VALUES (1, 3, 3, 1, 0, 0)

我想返回不同的 ProjectId、EmployeeId 对以及任何警告或过期:

SELECT DISTINCT ProjectId, EmployeeId FROM @Temp WHERE IsWarning = 1 OR IsExpired = 1

没问题。

但是,我还想返回 ProjectId、EmployeeId 对,其中 IsWarning = 0 和 IsExpired = 0 和 IsIncomplete = 1,但这对于所有 SomeTypeId (1、2、3) 都必须是正确的。换句话说,没有警告,没有过期,只是所有类别都不完整。

SomeTypeId Fks 到查找表。目前只有 3 个条目,但将来可能会有更多条目。

有任何想法吗?

我希望返回 ProjectId, EmployeeId (1, 1)。

4

3 回答 3

2

这使用MAXMIN确保所有值都相同;需要为+ 0每个位添加一个以使其可用于正常的数字聚合函数(如/// MIN... )MAXSUM

SELECT ProjectId, EmployeeId
FROM Temp
GROUP BY ProjectId, EmployeeId
HAVING MAX(IsWarning    + 0) = 0
   AND MAX(IsExpired    + 0) = 0
   AND MIN(IsIncomplete + 0) = 1

一个用于测试的 SQLfiddle

于 2013-02-15T18:06:36.967 回答
0

我不确定您的问题是要在 SAME 查询中获得这些结果,还是想要一个全新的查询。假设后者,您的查询将是:

SELECT DISTINCT ProjectId, EmployeeId FROM @Temp WHERE (IsWarning = 0 AND IsExpired = 0 AND IsIncomplete = 1)

假设前者,它将是:

SELECT DISTINCT ProjectId, EmployeeId FROM @Temp WHERE (IsWarning = 1 OR IsExpired = 1)

或(IsWarning = 0 AND IsExpired = 0 AND IsIncomplete = 1)

于 2013-02-15T18:06:35.600 回答
0

假设您没有重复记录,请尝试此操作;

请注意,假设您仍需要选择 data ,union则添加。如果您不需要它们,只需将其删除。WHERE IsWarning = 1 OR IsExpired = 1

SQL-DEMO 这里

;with cte as (
  select projectid, employeeid,
         case when sometypeid in (1,2,3) and 
                   IsWarning = 0 and IsExpired = 0 and IsIncomplete = 1
              then 1 else 0 end x
  from temp  
)
select projectid, employeeid 
from cte
group by projectId, employeeid
having sum(x) >= 3
union
select projectid, employeeid 
from Temp 
where IsWarning = 1 or IsExpired = 1
于 2013-02-15T18:30:52.907 回答