Select Count from One to Many Table - sql

I am using MS SQL.
I have a access group/permission one to many table setup for my security system. Users are assigned a Group. Each group can have a number of various permissions. I need a select statement that checks (returns a count) if a group has a specific permission.
The data I will have for the select statement is the GroupID of the User and the permissionName they are requesting access to.
Logically what I need is:
Get the ID of the permissionName. pID = SELECT permissionID FROM Permission_List WHERE permissionName = 'News'
Check Group_Permission Table to see if GroupID of the User intersects with permissionID equaling pID
If the count is 0 the group doesn't have access. If the count is 1 the group has access.(I'll handle this in PHP)
TABLE: Group_List
groupID groupName groupDesc
1 Standard Normal Access Level.
2 Limited Limited Access Level.
3 Medium Medium Access Level.
TABLE: Permission_List
permissionID permissionName permissionProtect permissionDesc
1 News 0 News section access.
2 Forums 0 Forums section access.
3 Contacts 0 Contact section access.
TABLE: Group_Permission
groupID permissionID
1 1
1 2
1 3
2 1
3 1
3 2

You should be able to JOIN the tables together and use the COUNT aggregate. For this example, I've assumed you are supplying a group id and a permission name.
SELECT COUNT(*)
FROM Group_Permission GP
JOIN Permission_List PL ON GP.permissionId = PL.permissionId
WHERE PL.permissionName = 'News'
AND GP.groupId = #someGroupId
If count is greater than 0, then the permission exists for that group.

Related

Check condition within table possibly self-join?

I have a users table with many columns however I am trying to use the below 2 columns to fetch the users do not have expired = 1
The query should return only user 2. Any help is much appreciated.
user_id expired
1 1
1 0
2 0
2 0
3 1
I know you have an answer, but if you are just looking for a list of single user_id's this might work a little more efficiently:
select user_id
from users
GROUP BY user_id
having MAX(expired) = 0
You can do this using not in like below :
select * from users where user_id
not in(select distinct user_id from users where expired = 1);
See SQL Here

Rails / ActiveRecord / SQL Return only 1 entry per user_id based on the highest priority

I have slightly complex relation going on my Rails application that I'm having a lot of trouble with.
For starters, there's a table that contains a list of roles which have an id and a priority. An example table looks like this
id priority
1 5
2 4
5 3
6 2
7 1
Now there's also a join_table that likes user ids with role ids in order to keep track of which user is assigned which role. The complicated part is that a user can have many roles
user_id role_id
3 1
3 2
3 7
4 1
4 5
4 6
What I'm trying to get is to filter done the users_roles table to only 1 entry per user based on the role with the lowest priority.
So what I'm trying to end up with is:
user_id role_id
3 7
4 6
The reason I would end up with this is due to the fact that roles 7 and 6 have the lowest priority.
Any help would be much appreciated
I'm pretty sure I might have solved this my self. The query I'm using is:
SELECT user_id, role_id, min(roles.priority)
FROM users_roles INNER JOIN roles
ON users_roles.role_id = roles.id
GROUP BY user_id

How do I include a column in a query that shows if item exists in another table?

I'm having what I hope is a momentary lapse of reasoning. I have the following schema:
SELECT RoleName FROM aspnet_Roles; gives:
-----------------------------------------
Administrator
Backend
Business Manager
Content Editor
Employee
Salesperson
SELECT RoleName FROM aspnet_Roles r INNER JOIN admin_page_role apr ON r.RoleId = apr.RoleId WHERE apr.PageId = 4;
------------------------------------------
Administrator
Business Manager
Salesperson
What I want is the full list of the first query along with whether or not the role is assigned, like:
| RoleName | IsAssignedToPage
---------------------------------------
Administrator 1
Backend 0
Business Manager 1
Content Editor 0
Employee 0
Salesperson 1
I looked at How to write a MySQL query that returns a temporary column containing flags... which makes sense, but my admin_page_role table is a bridge table that can contain many page-role combinations.
Something like this:
SELECT RoleName, case when apr.roleid is null then 0 else 1 end as IsAssignedToPage
FROM aspnet_Roles r
LEFT JOIN admin_page_role apr ON r.RoleId = apr.RoleId and apr.PageId = 4

Query Parent and Children from single table

I currently have a single table that hosts all of my users. Now some users have team_leaders which reference the user id of the team leader which is also stored in the database.
Now, what I wanted to do do (and can't figure out) is how to query the database where it retrieves a list of the ids of all the team members and the leader in one result set.
For Example
name | id | team_leader
--------------------------------------------------
Jack | 1 | null
--------------------------------------------------
Susan| 2 | 1
--------------------------------------------------
Bob | 3 | 1
--------------------------------------------------
Eric | 4 | null
--------------------------------------------------
SELECT name FROM users where team_leader = '<some user's id>'
returns [ 'Susan', Bob']
But I would like it to return the team leader included, such as
['Jack', 'Susan', 'Bob']
Does anyone have any idea how to include the team leader in the query results?
EDIT:
Okay, so it seems like I have not explained myself 100%, my apologies. so the goal of this query is to do as follows.
I have another table called leads and there is a field there that is called user_id which correlates to the user that has access to the lead. Now, I want to introduce the ability for team leaders to update the leads that are associated with their accounts, so if the current user is a team leader they should have the ability to update the user_id from their id to anyone on their team, from one of their children to another, and from one of the children to themselves, but not to anyone not on their team. So the way I thought of it was to have a WHERE EXISTS or a WHERE IN (this would mean adding a field to the lead table called leader_id) and it checks if the new user_id is in a list of that team leader's members, including themselves.
Based off the example above.
UPDATE lead SET user_id = xxx
WHERE lead.id = yyy
AND ...
-- here is where I would check that the user_id xxx is part of the current
-- user's team which must be a team leader, for example user.id = 1
So my thought process was to get the previous query to then check against.
Hope this clears things up.
If I'm understanding correctly, you can just use or:
select name
from users
where team_leader = 1 or id = 1
WITH CTE AS(
SELECT name,id,team_leader FROM [users]
WHERE team_leader=1
UNION ALL
SELECT u.name,u.id,u.team_leader from [users] u
JOIN CTE ON CTE.empno=u.team_leader`enter code here`
and u.team_leader=1
)
SELECT * FROM CTE

Count rows of right table when joinning two tables using SQL Query

I have a question about SQL Query. Let me do the example to illustration my issue:
I have two tables like this:
Roles Table
ID Role Role Description
1 Administrator Someone in administrator board
2 User Someone who has an account
3 Guess Someone who just view the website
Users Table
ID Username RoleID
1 trind08 1
2 trind09 1
3 trind10 1
4 kimchi 2
5 linhchi 2
6 thanh01 2
7 thanh02 3
8 kiemanh 3
9 liemanh 3
My issue is I want to view all roles and count the user who resolve to them.
Result table after running the query might look like this:
ID Role Role Description Cound of User
1 Administrator Someone in administrator board 3
2 User Someone who has an account 3
3 Guess Someone who just view the website 3
My first try to create a SQL Query like this:
select rol.*, usrCout as 'Count of User' from Roles rol
left join (select count(*) from Users where RoleID == rol.ID) usrCout;
But my query run unsuccessfully and I can't get the result I want. Please help me for this.
Thank you
SELECT
ID
,ROLE
,Role Description
,(SELECT COUNT(*) FROM Users where RoleID = rol.ID) AS UserCount
FROM Roles rol
Try this query
Select count(*) as 'Count of User', r.RoleID, Role, Role Description from role r, Users u where u.RoleId = r.Id group by r.RoleID,Role, Role Description;
Fiddle
Hope this helps