Question

I have 2 tables in database : 1. Agents table & 2. UserPermissions table

Table 1 Agents contains list of Agents as given below; here CompanyID & AgentID are unique values.

AgentID  AgentCode CompanyID RailEnabled  
1             A1        1          1  
2             A2        2          0  
3             A3        3          1  
4             A4        4          0  

Table 2 UserPermissions table contains list of all users who are coming under a particular agent. And there are 2 fields ModuleCode whose values are like 'RAL' for Rail in short and Enabled fields.

UserID UserName ModuleCode Enabled CompanyID

1   U1  RAL 1   1  
2   U2  RAL 0   1  
3   U3  RAL 1   1  
13  U4  BUS 1   1  
4   U1  RAL 0   2  
5   U2  RAL 0   2  
6   U3  RAL 0   2  
14  U4  HTL 1   2  
7   U1  RAL 0   3  
8   U2  RAL 0   3  
9   U3  RAL 0   3  
15  U4  FLT 1   3  
10  U1  RAL 0   4  
11  U2  RAL 0   4  
12  U3  RAL 0   4  
16  U4  BUS 1   4  
 

Now I need to filter out only the Agents for which RailEnabled is true but none of the users of that Agent is not enabled for Rail service(Module code: RAL).

Thanks for your help in advance.

Was it helpful?

Solution

Use NOT EXISTS.

SQLFiddle

select * from agents a
where railenabled = 1     --assuming 1 means enabled
and not exists (select 1  --not exists to remove all agents whose users have RAL enabled
                from userpermissions b
                where a.companyid = b.companyid
                and b.modulecode = 'RAL'
                and b.enabled = 1
                );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top