Stored procedure to return multiple records based on multiple conditions - sql

I am new to SQL server, thus looking for some quick help on writing stored procedure:
brief about what I am doing:
employee says he is expert (type) in different domains (industries) and willing to work in countries of choice (mycountries) and my sal (minsal)and my native country (orgcountry)
Employer says he need so and so expert in the his choice of domain (industries) in the countries where openings are there and with sal range.
employee table has lots of records with columns like this:
name, email, myindustries, mycountries, mytype,minsal
employer table has lots of records with columns like:
expertneed, inindustries, incountries, sal-from, sal-to
now when employee logs in, he/she should get all the records of matching employers
when employer logs in, he/she also get all the records of matching employees.
can some one help in writing sp for this? appreciate any help

If you're storing comma-separated ids then you'll need a function to split a string into multiple rows. This is how you would use it:
SELECT DISTINCT employee.name [employee], employer.name [employer]
FROM employee
OUTER APPLY dbo.split(employee.myindustries) myi (industry)
OUTER APPLY dbo.split(employee.mycountries) myc (country)
JOIN employer
OUTER APPLY dbo.split(employer.inindustries) ini (industry)
OUTER APPLY dbo.split(employer.incountries) inc (country)
WHERE employer.expertneed = employee.type
AND ini.inindustries = myi.industry
AND inc.incountries = myc.country
AND employee.minsal BETWEEN employer.[sal-from] AND employer.[sal-to]

Related

MS ACCESS Query with junction table, for all items in one table, but not in another

To create a many-to-many relationship, I have three tables:
tblEmployee, contains employees
tlkpPermission, contains 11 different possible permission groups an employee can be part of
tblEmployeeXPermission, combines the EmployeeID with one or more PermissionID
What I’m trying to create is a query that shows what permission groups an employee is NOT part of.
So, if EmployeeID 12345 is associated with PermissionID 1,2,3,4,5, but NOT 6,7,8,9,10,11 (in the EmployeeXPermission table) then I want the query to show EmployeeID 12345 is not part of PermissionID 6,7,8,9,10,11.
Of all the JOINs and query options, I can only get a query to show which PermissionIDs an employee is associated with, but not the PermissionIDs the employee is not associated with.
Any help would be appreciated.
Thanks
You need to start with all combinations of employees and permissions, and this type of join is CROSS JOIN, but MsAccess SQL does not have it in the new SQL syntax. You can use the old syntax of listing your tables in the FROM clause, comma separated, and provide the join condition, if any, in the WHERE clause:
SELECT
EmployeeId,
PermissionID
FROM
tblEmployee as E,
tlkpPermission as P
where not exists (
select 1
from tblEmployeeXPermission X
where X.EmployeeId=E.EmployeeId
and X.PermissionId=P.PermissionId
)
Here the part up to the WHERE clause would give you all employee - permission combinations, and the WHERE clause removes those occuring in the tblEmployeeXPermission, leaving you with the ones you want.

SQL Query Involving Data From Different Tables

I have two different tables with records I need to join together in a way I can't quite figure out how to make work. My data looks like this.
Table A
Columns: Employee_ID, Employee_Department, Employee_Team, Manager_ID, Is_a_Manager ... many other columns
Sample Values:
12345 Department1 Team1 67890 Yes/No
.
.
.
One employee per row, several thousand rows comprising the entire company
Table B
Employee_ID, Manager_ID ... other columns
The exact same data set as Table A
Currently I'm combining those two tables (and three others) with a simple join on Employee_ID, which I'm then using as a data source in Tableau to visualize the data.
What I'd like to do with a SQL script is as follows:
Check to see whether an employee in Table A is a manager or not based on the Is_a_Manager column
If they are, find an employee in Table B who is one of their direct reports by matching the employee ID in Table A to the Manager ID in Table B.
Lookup that direct report's department and team in Table A by matching the Employee_ID in Table B to Employee_ID in Table A and displaying the Employee_Department and Employee_Team columns.
Add the direct report's department and team to two new columns in the original manager's Table A row
I'd like the final output in Table A to be something like
Employee_ID, Employee_Department, Employee_Team, Manager_ID, Is_a_Manager? ... Direct_Report_Department, Direct_Report_Team
Also, an important point is that some managers will have employees who are on different teams, so values in the Direct_Report_Department and Direct_Report_Team are not distinct. I only actually need any one employee's Department and Team to display, it doesn't matter which employee's it is.
Finally, I am able to do step 1 fairly easily in Tableau, so if the SQL script could do steps 2-4 and simply return a null value if the employee was not a manager, that would work for me as well.
Any ideas on how to accomplish this would be greatly appreciated. Thank you!
This should work based on the requirement provided. You don’t have to do any of the steps in Tableau and can simply export the output from the SQL as your data source
Select Tb1.Employee_ID, Tb1.Employee_Department, Tb1.Employee_Team, Tb1.Manager_ID, Tb1.Is_a_Manager, Tb3. Direct_Report_Department, Tb3. Direct_Report_Team
from Table_A Tb1
join (Select Manager_id, max(Employee_id) as emp_id from Table_B group by Manager_id) Tb2
on Tb1.Employee_id = Tb2.Manager_id
left join (Select Employee_ID, Employee_Department as Direct_Report_Department, Employee_Team as Direct_Report_Team from Table_A group by Employee_ID, Employee_Department, Employee_Team) Tb3
on Tb2.emp_id = Tb3.Employee_ID
where Tb1.Is_a_Manager = 'Yes';

Which Oracle query is faster

I am trying to display employee properties using C# WPF view.
I have data in '2' different oracle tables in my database:
Those tables structure at high-level is...
Employee table (EMP) - columns:
ID, Name, Organisation
Employee properties table (EMPPR) - columns
ID, PropertyName, PropertyValue
The user will input 'List of Employee Name' and I need to display Employee properties using data in those '2' tables.
Each employee has properties from 40-80 i.e. 40-80 rows per employee in EMPPR table. In this case, which approach is more efficient?
Approach #1 - single query data retrieval:
SELECT Pr.PropertyName, Pr.PropertyValue
FROM EMP Emp, EMPPR Pr
WHERE Emp.ID = Pr.ID
AND Emp.Name IN (<List of Names entered>)
Approach #2 - get IDs list using one query and Get properties using that ID in the second query
Query #1:
SELECT ID
FROM EMP
WHERE Name IN (<List of Names entered>)
Query #2:
SELECT PropertyName, PropertyValue
FROM EMPPR
WHERE ID IN (<List of IDs got from Query#1>)
I need to retrieve ~10K employee details at once where each employee has 40-80 properties.
Which approach is good?
Which query is faster?
The first one, which uses a single query to fetch your results.
Why? much of the elapsed time handling queries, especially ones with modestly sized rows like yours, is consumed going back and forth from the client to the database server.
Plus, the construct WHERE something IN (val, val, val, val ... ... val) can throw an error when you have too many values. So the first query is more robust.
Pro tip: Come on into the 21st century and use the new JOIN syntax.
SELECT Pr.PropertyName, Pr.PropertyValue
FROM EMP Emp
JOIN EMPPR Pr ON Emp.ID = Pr.ID
WHERE Emp.Name IN (<List of Names Inputted>)
Use first approach of join between two tables which is far better than using where clause two times.

SQL Query multiple tables same values

I'm having an issue creating a query. Here are the specifics.
There are 2 tables company_career and company_people.
People contains person information (Name, Address, etc) and Career contains historical career information (job_title, department, etc.)
People is linked to Career by job_ref_id.
Direct_Report_id lies in the career table and contains a unique id that correlates to job_ref_id.
Example: job_ref_id = '1' results in direct_report_id ='A'. I then use the value produced from direct-report_id (i.e., 'A') and query the job_ref_id = 'A' and this produces the employee name. Since it produces the employee name (which is actually the manager) I need to know how I would query this to present this as the manager name.
I think I know what you are looking for, you just need to use joins and aliases. For example:
SELECT
cp.name AS [EmployeeName],
cp.address AS [EmployeeAddress],
cc.job_title AS [EmployeeTitle],
cc.department AS [EmployeeDept],
m.name AS [ManagerName]
FROM company_people cp
LEFT JOIN company_career cc ON cc.job_ref_id = cp.job_ref_id
LEFT JOIN company_people m ON m.job_ref_id = cc.direct_report_id

Ms-Access: counting from 2 tables

I have two tables in a Database
and
I need to retrieve the number of staff per manager in the following format
I've been trying to adapt an answer to another question
SELECT bankNo AS "Bank Number",
COUNT (*) AS "Total Branches"
FROM BankBranch
GROUP BY bankNo
As
SELECT COUNT (*) AS StaffCount ,
Employee.Name AS Name
FROM Employee, Stafflink
GROUP BY Name
As I look at the Group BY I'm thinking I should be grouping by The ManID in the Stafflink Table.
My output with this query looks like this
So it is counting correctly but as you can see it's far off the output I need to get.
Any advice would be appreciated.
You need to join the Employee and Stafflink tables. It appears that your FROM clause should look like this:
FROM Employee INNER JOIN StaffLink ON Employee.ID = StaffLink.ManID
You have to join the Eployee table twice to get the summary of employees under manager
select count(*) as StaffCount,Manager.Name
from Employee join Stafflink on employee.Id = StaffLink.EmpId
join Employee as Manager on StaffLink.ManId = Manager.Id
Group by Manager.Name
The answers that advise you on how to join are correct, assuming that you want to learn how to use SQL in MS Access. But there is a way to accomplish the same thing using the ACCESS GUI for designing queries, and this involves a shorter learning curve than learning SQL.
The key to using the GUI when more than one table is involved is to realize that you have to define the relationships between tables in the relationship manager. Once you do that, designing the query you are after is a piece of cake, just point and click.
The tricky thing in your case is that there are two relationships between the two tables. One relationship links EmpId to ID and the other links ManId to ID.
If, however, you want to learn SQL, then this shortcut will be a digression.
If you don't specify a join between the tables, a so called Cartesian product will be built, i.e., each record from one table will be paired with every record from the other table. If you have 7 records in one table and 10 in the other you will get 70 pairs (i.e. rows) before grouping. This explains why you are getting a count of 7 per manager name.
Besides joining the tables, I would suggest you to group on the manager id instead of the manager name. The manager id is known to be unique per manager, but not the name. This then requires you to either group on the name in addition, because the name is in the select list or to apply an aggregate function on the name. Each additional grouping slows down the query; therefore I prefer the aggregate function.
SELECT
COUNT(*) AS StaffCount,
FIRST(Manager.Name) AS ManagerName
FROM
Stafflink
INNER JOIN Employee AS Manager
ON StaffLink.ManId = Manager.Id
GROUP BY
StaffLink.ManId
I don't know if it makes a performance difference, but I prefer to group on StaffLink.ManId than on Employee.Id, since StaffLink is the main table here and Employee is just used as lookup table in this query.