2013-10-21 39 views
0

我的数据代理是组的一部分。每个代理可以以多种状态许可。我正在尝试执行一个查询,该查询采用客户端状态并检查组中的每个代理程序是否在客户端状态下获得许可。SQL SERVER - 查找具有相同特征的组的成员

这里是样本数据:

CREATE TABLE GroupAgentState (
GroupID int, 
AgentID int, 
StateCd CHAR(2)) 

INSERT INTO GroupAgentState VALUES 
(1,100, 'OH'), 
(1, 100, 'NH'), 
(1,100,'NY'), 
(1, 101, 'OH'), 
(1, 101, 'NY'), 
(1, 102, 'NY') 

我想要做一个检查,以便如果我有一个客户端状态(@ClientState)和客户端与组之间的关系,是该组中的所有代理在客户端状态许可?

对于我的示例数据,我期望如果客户端A与组1和@ClientState ='OH'有关系,那么返回值将是错误的。如果@ClientState ='NY',那么返回值将为true。

我在我头上的这一个...

在此先感谢!

+0

那你试试这么远吗? –

回答

0

该查询显示,未在客户国注册任何代理:

SELECT AgentID 
FROM GroupAgentState gas1 
WHERE GroupID = @testGroup 
    AND StateCd <> @ClientState 
    AND NOT EXISTS(Select * 
        From GroupAgentState gas2 
        Where gas2.StateCd = @ClientState 
        And gas2.GroupID = gas1.GroupID 
        And gas2.AgentID = gas1.AgentID 
       ) 
0

这可能是你一个良好的开端:

-- returns count of agents unlicensed in a particular state (@ClientState) by group 
select 
    gas.GroupId 
    , sum(case when gas.AgentId is null then 1 else 0 end) UnlicensedAgents 
from 
    Agent a 
    left outer join GroupAgentState gas 
    on a.AgentId = gas.AgentId 
     and gas.StateCd = @ClientState 
group by 
    gas.GroupId 
+0

感谢莫霍 - 我正在考虑走上重要路线,但我希望有一个更迷人的解决方案... – user2904136

相关问题