SQL: Displaying and counting items in - sql

I'm trying to count staff that belong to certain branch in sql, so branch X has Y number of employees for example. There are two tables I need to query number 1. and 2. below. I want to achieve the following:branchno | number of staff in that branch
The 'Staff' table: staffno | fname | lname | position | sex | dob | salary | branchno
the 'branch' table: branchno | street | city | postcode
Thank you kindly

This is a really basic query, and if you have problems solving it, just break it down step by step:
What is it you want to get? A count of people in a certain branch. How do you choose what information to display? With a selectstatement.
What do you want to do with the information before you show it? You want to count it with a count()aggregate function.
Where do you get the data from? A table, selected with a fromstatement.
And finally, you only want from a specific branch so what do you do? You filter the results with a whereclause.
And putting it all together you get this:
SELECT COUNT(staffno) FROM Staff WHERE branchno = 1
If you want the branch with number 1.
Edit: I just noticed the comment you made about branches without employees, and taking that into account you need the branch table too.
SELECT b.branchno, COUNT(staffno) AS StaffCount FROM branch b
LEFT JOIN staff s ON b.branchno = s.branchno
-- WHERE b.branchno = 1 -- optional filter
GROUP BY b.branchno
Using a left joinbetween the tables means that you'll get all rows from branch and the matching rows from staff.

Related

select users with same social security number different badge numbers

Hello as the title suggest I need help writing a query that does this. I need to find all the users who have had a badge number change. So in the database there are often two records for the same person but both have a different badge number. Im assuming it's the same person if the social matches.
Table:
Badge_no | SSN
123123 | 387-47-1234 2
34837 | 387-47-1234
837532 | 543-45-6392
584391 | 543-45-6392
In this case I would want it to output:
837532 | 543-45-6392
584391 | 543-45-6392
Thank you!
I believe the following should do the trick here:
SELECT *
FROM yourtable
WHERE SSN IN (SELECT SSN FROM yourtable GROUP BY SSN HAVING Count(*) >=2);
That subquery will return SSN's that have more than one record. We use those SSN's to select, again, from the table to get all of the fields associated to them.

Subquery in FROM clause

Looking around in the (now-discontinued) documentation and found this example:
Subquery in FROM clause
A subquery in a FROM clause acts similarly to a temporary table that is generated during the execution of a query and lost afterwards.
SELECT Managers.Id, Employees.Salary
FROM (
SELECT Id
FROM Employees
WHERE ManagerId IS NULL
) AS Managers
JOIN Employees ON Managers.Id = Employees.Id
(Excerpted from Subqueries - Subquery in FROM clause. The original author was Phrancis. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 1030 and example ID: 3327.)
My question is:
why using an extra ManagerId. An Id column is already in
Employees table,
why have the extra ManagerId to be null for a manager (ok it wants to be a joke).
My opinion:
despite the upvotes, something is wrong with this is example,
Tables with example data would be nice to see on the fly how it's working. One table with start data, one table temporary SELECT and one table the
resultset.
Edit: Thanks to all contributors for their answers!
#Alex K.: That is my point of view "it is not something one would actually use". But people, who wants to learn SQL, might think, that it is good practice, because it is in the documentation here.,
#Nebi: Thanks for the point that one would write it simpler to get the same result.
#Unnikrishnan R: "showcase how the sub query works" does in my eyes not only mean that it is fully functional but additional that it makes sense. If I get things simpler, why doing it the errorprone hard way.
#me: should have titled it "let's discuss sql documentation" or like that ;)
Let us consider a situation where Employee table holds all employees including their managers in which employee has an Id, and there is also a column for the manager Id (which can be null). This can be the point of view ,who was writing that SQL queries.
For Example,
+----+-------+--------+-----------+
| Id | Name | Salary | ManagerId |
+----+-------+--------+-----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
+----+-------+--------+-----------+
why have the extra ManagerId to be null for a manager --
getting the employees that are not managers
It is just an example how to do/ use Subqueries.
To your questions:
why using an extra ManagerId. An Id column is already in Employees
table
First of all ManagerId and Id are different columns of the table Employees. So there is a difference between them. But you might reffering to the Id of the Subquery Managers and the Id of the joined table Employees.
Then you need to define which Id you are using. Else you get the Error for ambigiuos column. In this example you to specify either the Subqueries Id which is Managers.Id or the Id of the joined table Employees (Employees.Id). Which one you choose is totally regardless because you use INNER JOIN one the Id.
why have the extra ManagerId to be null for a manager (ok it wants
to be a joke).
This is because of getting all the Employees that have are not managers. You are right about saying this could be done easier or in other form. For instance:
SELECT Id, Salary
FROM Employees
WHERE ManagerId IS NULL
This probably gets the same result as in the original. But the example is not about that, it is about the structure of a subquery.
why using an extra ManagerId. An Id column is already in Employees table
Consider you are having an employee table and you also wanted to keep the manager information in the same table.so apart from the ID column you need to add another column to keep the managerid.
why have the extra ManagerId to be null for a manager (ok it wants to be a joke).
The query is just to showcase how the sub query works. In this case subquery retrieves the manager from the Employee table (managerID is null) then join those id's with Employee table in the outer query to get the salary of each managers.

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

How do I make a query for if value exists in row add a value to another field?

I have a database on access and I want to add a value to a column at the end of each row based on which hospital they are in. This is a separate value. For example - the hospital called "St. James Hospital" has the id of "3" in a separate field. How do I do this using a query rather than manually going through a whole database?
example here
Not the best solution, but you can do something like this:
create table new_table as
select id, case when hospital="St. James Hospital" then 3 else null
from old_table
Or, the better option would be to create a table with the columns hospital_name and hospital_id. You can then create a foreign key relationship that will create the mapping for you, and enforce data integrity. A join across the two tables will produce what you want.
Read about this here:
http://net.tutsplus.com/tutorials/databases/sql-for-beginners-part-3-database-relationships/
The answer to your question is a JOIN+UPDATE. I am fairly sure if you looked up you would find the below link.
Access DB update one table with value from another
You could do this:
update yourTable
set yourFinalColumnWhateverItsNameIs = {your desired value}
where someColumn = 3
Every row in the table that has a 3 in the someColumn column will then have that final column set to your desired value.
If this isn't what you want, please make your question clearer. Are you trying to put the name of the hospital into this table? If so, that is not a good idea and there are better ways to accomplish that.
Furthermore, if every row with a certain value (3) gets this value, you could simply add it to the other (i.e. Hospitals) table. No need to repeat it everywhere in the table that points back to the Hospitals table.
P.S. Here's an example of what I meant:
Let's say you have two tables
HOSPITALS
id
name
city
state
BIRTHS
id
hospitalid
babysname
gender
mothersname
fathername
You could get a baby's city of birth without having to include the City column in the Births table, simply by joining the tables on hospitals.id = births.hospitalid.
After examining your ACCDB file, I suggest you consider setting up the tables differently.
Table Health_Professionals:
ID First Name Second Name Position hospital_id
1 John Doe PI 2
2 Joe Smith Co-PI 1
3 Sarah Johnson Nurse 3
Table Hospitals:
hospital_id Hospital
1 Beaumont
2 St James
3 Letterkenny Hosptial
A key point is to avoid storing both the hospital ID and name in the Health_Professionals table. Store only the ID. When you need to see the name, use the hospital ID to join with the Hospitals table and get the name from there.
A useful side effect of this design is that if anyone ever misspells a hospital name, eg "Hosptial", you need correct that error in only one place. Same holds true whenever a hospital is intentionally renamed.
Based on those tables, the query below returns this result set.
ID Second Name First Name Position hospital_id Hospital
1 Doe John PI 2 St James
3 Johnson Sarah Nurse 3 Letterkenny Hosptial
2 Smith Joe Co-PI 1 Beaumont
SELECT
hp.ID,
hp.[Second Name],
hp.[First Name],
hp.Position,
hp.hospital_id,
h.Hospital
FROM
Health_Professionals AS hp
INNER JOIN Hospitals AS h
ON hp.hospital_id = h.hospital_id
ORDER BY
hp.[Second Name],
hp.[First Name];

UPDATE query that fixes orphaned records

I have an Access database that has two tables that are related by PK/FK. Unfortunately, the database tables have allowed for duplicate/redundant records and has made the database a bit screwy. I am trying to figure out a SQL statement that will fix the problem.
To better explain the problem and goal, I have created example tables to use as reference:
alt text http://img38.imageshack.us/img38/9243/514201074110am.png
You'll notice there are two tables, a Student table and a TestScore table where StudentID is the PK/FK.
The Student table contains duplicate records for students John, Sally, Tommy, and Suzy. In other words the John's with StudentID's 1 and 5 are the same person, Sally 2 and 6 are the same person, and so on.
The TestScore table relates test scores with a student.
Ignoring how/why the Student table allowed duplicates, etc - The goal I'm trying to accomplish is to update the TestScore table so that it replaces the StudentID's that have been disabled with the corresponding enabled StudentID. So, all StudentID's = 1 (John) will be updated to 5; all StudentID's = 2 (Sally) will be updated to 6, and so on. Here's the resultant TestScore table that I'm shooting for (Notice there is no longer any reference to the disabled StudentID's 1-4):
alt text http://img163.imageshack.us/img163/1954/514201091121am.png
Can you think of a query (compatible with MS Access's JET Engine) that can accomplish this goal? Or, maybe, you can offer some tips/perspectives that will point me in the right direction.
Thanks.
The only way to do this is through a series of queries and temporary tables.
First, I would create the following Make Table query that you would use to create a mapping of the bad StudentID to correct StudentID.
Select S1.StudentId As NewStudentId, S2.StudentId As OldStudentId
Into zzStudentMap
From Student As S1
Inner Join Student As S2
On S2.Name = S1.Name
Where S1.Disabled = False
And S2.StudentId <> S1.StudentId
And S2.Disabled = True
Next, you would use that temporary table to update the TestScore table with the correct StudentID.
Update TestScore
Inner Join zzStudentMap
On zzStudentMap.OldStudentId = TestScore.StudentId
Set StudentId = zzStudentMap.NewStudentId
The most common technique to identify duplicates in a table is to group by the fields that represent duplicate records:
ID FIRST_NAME LAST_NAME
1 Brian Smith
3 George Smith
25 Brian Smith
In this case we want to remove one of the Brian Smith Records, or in your case, update the ID field so they both have the value of 25 or 1 (completely arbitrary which one to use).
SELECT min(id)
FROM example
GROUP BY first_name, last_name
Using min on ID will return:
ID FIRST_NAME LAST_NAME
1 Brian Smith
3 George Smith
If you use max you would get
ID FIRST_NAME LAST_NAME
25 Brian Smith
3 George Smith
I usually use this technique to delete the duplicates, not update them:
DELETE FROM example
WHERE ID NOT IN (SELECT MAX (ID)
FROM example
GROUP BY first_name, last_name)