SQL Query multiple tables same values - sql

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

Related

How to distinguish these two ID requests when joining tables?

SQL noob here. I have a database of soccer matches that I am trying to learn/practice SQL with.
In one table (called "Match") there is the match_api_id, date, home_team_api_id, away_team_api_id, home_team_goal, away_team_goal.
In another table (called "Team") there is the team_api_id, team_long_name.
Right now I am trying to do a query to show the ID of the match, the date, the home team's name, and the away team's name.
SELECT M.match_api_id, M.date, T.team_long_name, T.team_long_name
FROM Match M
JOIN Team T ON (M.home_team_api_id = T.team_api_id)
JOIN Team T ON (M.away_team_api_id = T.team_api_id)
LIMIT 10
This code worked when I only used one join (the first one) to show the home team's name. However, when I add the second join it gives me the ambiguous column name error. How do I alter this code so that I can also display the away team's name?
YOu need different table aliases. Otherwise T is ambiguous:
SELECT M.match_api_id, M.date, TH.team_long_name, TA.team_long_name
FROM Match M JOIN
Team TH
ON M.home_team_api_id = TH.team_api_id JOIN
Team TA
ON M.away_team_api_id = TA.team_api_id;
LIMIT 10

Oracle: What is the best way to use two tables in a mutually exclusive way?

I have the following sample query
select a.name,c.company
from employee a, company c
where a.comp_id = c.comp_id
and a.active='Y'
Now I have two new tables
company_profile, (Profile values for each company. Each company may or may not have data in this table)
profile_defaults (contains default profile values for each profile item independent of company)
Now I need to refer to column "show_data" in company_profile for a specific company. If there is no row for that company then i need to take the value from the profile_defaults table. How do I integrate this logic in the first query which I mentioned above in the best possible way.
Table
Employee
|Name|Comp_id|active|
Company
|Comp_id|Name|
Company_Profile
|comp_profile_id|profile_id|comp_id|profile_name|profile_value|
Profile_Defaults
|profile_id|profile_name|profile_value|
There are many other tables used. But I shortened it for four tables alone for this case now.
Try using this query:
SELECT a.name, c.company, NVL(cp.profile_value, pd.profile_value)
FROM employee a INNER JOIN company c
ON a.comp_id = c.comp_id
LEFT JOIN company_profile cp
ON c.comp_id = cp.comp_id
LEFT JOIN profile_defaults pd
ON cp.profile_id = pd.profile_id
This solution assumes that you have columns comp_id in both the company_profile and default profile_defaults tables to which you can join a record for a given company. As #PM77-1 mentioned, I use NVL() to first check the company_profile table, and default to profile_defaults if nothing is found in the former.

Needing 2 different ID's from the same ID Table

I am pulling reports for my company and am needing to pull a specific report that I am having trouble with. We are using SQL Server 2012 and I am pulling the SQL reports.
What I need is to pull a simple report:
Group Name, List of Members in the group; Supervisor of the group.
However, the problem is that the supervisor as well as the members and the group name all come from one table in order to get the relevant information. Currently here is my SQL code below:
Use DATABASE
go
-- This is the select portion deciding the columns needed.
select
C.group_name
,C2.first_name
,C2.last_name
-- These are the tables that the query is pulling from.
FROM db..groups AS G
LEFT OUTER JOIN db..contact AS C
ON G.group_id=C.contact_id
INNER JOIN db..contact AS C2
ON G.member=C2.contact_id
go
This pulls the first portion:
The group name, then the first name of a member in that group, and then the last name of a member in that group.
However, I am having trouble getting the supervisor portion. This portion uses the table db.contact under the column supervisor_id as a foreign key. The supervisor_id uses the same unique id as the normal contact_id, but in the same table. Some contact_ids have supervisor_id's that are other contact_id's from the same table, hence the foreign key.
How can I make it so I can get the contact_id that is equal to the supervisor_id of the contact_id that is equal to the group_id?
Taking a quick stab at this while we wait for details
You know you need groups and I'm assuming you don't care about Groups that have no members. Thus Groups INNER JOINed to Contact. This generates your direct group membership. To get the supervisor, you then need to factor in the Supervisor on the specific Contact row.
You might not have a boss, or your boss might be yourself. It's always interesting to see how various HR systems record this. In my example, I'm assuming the head reports to no one instead of themselves.
SELECT
G.group_name
, C.first_name
, C.last_name
-- this may produce nulls depending on outer vs inner join below
, CS.first_name AS supervisor_first_name
, CS.last_name AS supervisor_last_name
FROM
dbo.Groups AS G
INNER JOIN
dbo.Contact AS C
ON C.contact_id = G.member
LEFT OUTER JOIN
dbo.Contact AS CS
ON CS.contact_id = C.supervisor_id;
Depending on how exactly you wanted that data reported, there are various tricks we could use to report that data. In particular, GROUPING SETS might come in handy.
SQLFiddle

Best way to structure SQL Query

I have several database tables:
Client (basic info, first name, last name, etc)
Employer (basic info, employer name, fax, address, etc.)
I then have a junction table linking the two tables if required:
Client_Employer (ClientID, EmployerID)
All of these tables are maintained with confirmed, accurate, clean data.
I have a fourth table that is used for informational purposes only and the data is neither clean, nor reliable as it is supplied by the end user and cannot be confirmed.
ClientEmployer (data supplied by the client regarding their current employer)
I want to write a query that returns Client/Employer data if a record exists in the Client_Employer table, but will also fallback to the ClientEmployer table for employer information if none exists otherwise.
The columns in Employer match exactly the same columns in ClientEmployer.
I have looked at several options using ISNULL(), CASE, IF/ELSE, etc. but just want to see what others think the best, cleanest way to do this will be?
Well, making a few assumptions about the schema for ClientEmployer table, I'd combine a UNION and an EXISTS like this:
SELECT
cl.ClientID as ClientID,
em.EmployerID as employerID,
cl.firstname,
cl.lastname,
em.employername,
em.fax,
em. address
FROM
Client cl,
Employer em,
Client_Employer ce
WHERE
cl.ClientID = ce.ClientID
and em.EmployerID = ce.EmployerID
UNION
SELECT
Clem.ClientID as clientID,
-1 as EmployerID,
clem.firstname, clem.lastname,
clem.employername,
clem.fax,
clem.address
FROM
ClientEmployer clem
WHERE
NOT EXISTS (
SELECT * FROM Client cl, Employer em, Client_Employer ce
WHERE cl.ClientID = ce.ClientID
and em.EmployerID = ce.EmployerID
and clem.ClientID = cl.ClientID
and clem.EmployerName = ce.EmployerName)
I think you should use ISNULL() to LEFT JOIN Employer, like this:
SELECT
Client.*,
Employer.*
FROM Client
LEFT JOIN Client_Employer
ON Client_Employer.client_id = Client.id
LEFT JOIN ClientEmployer
ON ClientEmployer.client_id = Client.id
LEFT JOIN Employer
ON Employer.id = ISNULL(Client_Employer.employer_id, ClientEmployer.employer_id)
WHERE Employer.id IS NOT NULL;
If some Employer.id is NULL (WHERE clause) so there aren't a relationship from a given Client.id in both Client/Employer tables, which means you'll have just the data which is in some of the Client/Employer tables.
Hope it works as you expect.
What about the usage of IF EXISTS? Seems like you could pretty easily retrieve data where it exists, else select from ClientEmployer in your example where it does not exist.

SQL WHERE <from another table>

Say you have these tables:
PHARMACY(**___id_pharmacy___**, name, addr, tel)
PHARMACIST(**___Insurance_number___**, name, surname, qualification, **id_pharmacy**)
SELLS(**___id_pharmacy___**, **___name___**, price)
DRUG(**___Name___**, chem_formula, **id_druggistshop**)
DRUGGISTSHOP(**___id_druggistshop___**, name, address)
I think this will be more specific.
So, I'm trying to construct an SQL statement, in which I will fetch the data from id_pharmacy and name FROM PHARMACY, the insurance_number, name, and surname columns from PHARMACIST, for all the pharmacies that sell the drug called Kronol.
And that's basically it. I know I'm missing the relationships in the code I wrote previously.
Note: Those column names which have underscores left and right to them are underlined(Primary keys).
The query you've written won't work in any DBMS that I know of.
You'll most likely want to use some combination of JOINs.
Since the exact schema isn't provided, consider this pseudo code, but hopefully it will get you on the right track.
SELECT PH.Ph_Number, PH.Name, PHCL.Ins_Number, PHCL.Name, PHCL.Surname
FROM PH
INNER JOIN PHCL ON PHCL.PH_Number = PH.Ph_Number
INNER JOIN MLIST ON MLIST.PH_Number = PH.PH_Number
WHERE MLIST.Name = "Andy"
I've obviously assumed some relationships between tables that may or may not exist, but hopefully this will be pretty close. The UNION operator won't work because you're selecting different columns and a different number of columns from the various tables. This is the wrong approach all together for what you're trying to do. It's also worth mentioning that a LEFT JOIN may or may not be a better option for you, depending on the exact requirements you're trying to meet.
Ok, try this query:
SELECT A.id_pharmacy, A.name AS PharmacyName, B.Insurance_number,
B.name AS PharmacistName, B.surname AS PharmacistSurname
FROM PHARMACY A
LEFT JOIN PHARMACIST B
ON A.id_pharmacy = B.id_pharmacy
WHERE A.id_pharmacy IN (SELECT id_pharmacy FROM SELLS WHERE name = 'Kronol')