选择与所有标准匹配的人员

时间:2014-11-07 12:14:59

标签: sql sql-server sql-server-2008

我正在尝试运行查询但无法获取

这是结构:

Person:
  IdPerson
  FirstName
  LastName
  ...

CustomField
  IdField
  ....

CustomFieldXPerson
  IdField
  IdPerson
  Value

Filter:
  IdField
  Value
  Criteria (<, >, <=, >=, =)
  GroupId

我需要让所有与所有过滤器匹配的人,并让所有匹配至少一个人...

SELECT IdPerson
FROM Person p
  JOIN CustomFieldXPerson cfxp on cfxp.IdPerson = p.IdPerson
  JOIN Filter f on f.IdField = cfxp.IdField AND f.Value (f.Criteria) cfxp.Value
WHERE f.GroupId = X 

有一种简单的方法可以动态地执行此操作吗?

1 个答案:

答案 0 :(得分:2)

您可以将您的查询表达为:

SELECT IdPerson
FROM Person p JOIN
     CustomFieldXPerson cfxp
     on cfxp.IdPerson = p.IdPerson JOIN
     Filter f
     on f.IdField = cfxp.IdField AND
        (f.Criteria = '=' and f.Value = cfxp.Value or
         f.Criteria = '<' and f.Value < cfxp.Value or
         f.Criteria = '<=' and f.Value <= cfxp.Value or
         f.Criteria = '>' and f.Value > cfxp.Value or
         f.Criteria = '>=' and f.Value >= cfxp.Value
        )         
WHERE f.GroupId = X ;

编辑:

如果您想获得符合所有过滤条件的人,请使用group by

SELECT IdPerson
FROM Person p JOIN
     CustomFieldXPerson cfxp
     on cfxp.IdPerson = p.IdPerson LEFT JOIN
     Filter f
     on f.IdField = cfxp.IdField AND
        (f.Criteria = '=' and f.Value = cfxp.Value or
         f.Criteria = '<' and f.Value < cfxp.Value or
         f.Criteria = '<=' and f.Value <= cfxp.Value or
         f.Criteria = '>' and f.Value > cfxp.Value or
         f.Criteria = '>=' and f.Value >= cfxp.Value
        ) AND      
        f.GroupId = X
GROUP BY idPerson
HAVING COUNT(f.IdField) = COUNT(*) OR COUNT(f.IdField) = 0;

换句话说,与群组中的人匹配的所有过滤器都匹配。 HAVING子句中的附加条件是过滤器组没有过滤器。