SQL Join query, getting ManagerName - tsql

I have an tblEmployeeProfile & a tblPersonnel. tblPersonnel is an HR table, that consists of all employees in the company; tblEmployeeProfile contains details about an employee's position.
tblPersonnel.PersonnelID
tblPersonnel.FirstName
tblPersonnel.MiddleName
tblPersonnel.LastName
tblPersonnel.PhoneNumber
tblPersonnel.Email
tblEmployeeProfile.EmployeeID
tblEmployeeProfile.ManagerID
tblEmployeeProfile.DepartmentID
tblEmployeeProfile.JobCategoryID
tblEmployeeProfile.SalaryID
I want to return a record with the following fields:
EmployeeID, FirstName, MiddleName, LastName, Email, ManagerFullName
where EmployeeID = #EmployeeID
*tblEmployeeProfile.ManagerID = tblPersonnel.PersonnelID*
I can't seem to get the query correct for getting the ManagerFullName

Not sure if it's the same for Tsql, but you're going to need two join statements. 1st join is the employee profile table to your personnel table. Second is to join the personnel table to to the profile table to grab the manager name. Might look something like this
FROM personnel p
JOIN employeeprofile prof
ON prof.employeeID = p.personnelID
LEFT OUTER JOIN personnel man
ON man.personnelID = prof.managerID
The only reason I did a left outer join on the manager stuff is in the odd event a user might not have a manager assigned.

You may want to try the following:
SELECT
e1.EmployeeID,
e1.FirstName,
e1.MiddleName,
e1.LastName,
e1.Email,
e2.FirstName + ' ' + e2.LastName AS ManagerFullName
FROM
tblPersonnel e1
INNER JOIN
tblEmployeeProfile ep ON (ep.EmployeeID = e1.PersonnelID)
INNER JOIN
tblPersonnel e2 ON (e2.PersonnelID = ep.ManagerID)
WHERE
e1.EmployeeID = #EmployeeID

SELECT
employee.PersonnelID, employee.FirstName, employee.MiddleName, employee.LastName, employee.Email, manager.FirstName + ' ' + manager.Surname
FROM
tblPersonnel AS employee
INNER JOIN tblEmployeeProfile ON employee.PersonnelID = tblEmployeeProfile.EmployeeID
INNER JOIN tblPersonnel AS manager ON tblEmployeeProfile.ManagerID = manager.PersonnelID
WHERE
employee.PersonnelID = #EmployeeID

Try this:
SELECT
p1.PersonnelID,
p1.FirstName,
p1.MiddleName,
p1.LastName,
p1.Email,
p2.FirstName + ' ' + p2.MiddleName + ' ' + p2.LastName as ManagerFullName
FROM
tblEmployeeProfile e,
tblPersonnel p1,
tblPersonnel p2
WHERE
e.EmployeeId = p1.PersonnelId AND
e.ManagerId = p2.PersonnelId AND
e.EmployeeId = #EmployeeId

select p.EmployeeID
, E.FirstName
, E.MiddleName
, E.LastName
, E.Email
, M.FirstName
+ ' '
+ M.MiddleName
+ ' '
+ M.LastNameas as ManagerFullName
from tblPersonnel p
join tblEmployeeProfile as E on p.PersonnelID=E.EmplyeeID
join tblEmployeeProfile as M on M.PersonnelID=E.ManagerID
where E.EmplyeeID=#EmployeeID
assuming of course:
tblPersonnel.PersonnelID = tblEmployeeProfile.EmployeeID
every person has a manager (this means the CEO will be missing when you as for him/her)

Are you trying to do something like this?
Select
EmployeeID
,empTable.FirstName
,empTable.MiddleName
,empTable.LastName
,empTable.Email
,mgrTable.FirstName + ' '
+ mgrTable.MiddleName + ' '
+ mgrTable.LastName
as ManagerFullName
from
tblEmployeeProfile
inner join
tblPersonnel as empTable
on tblEmployeeProfile.EmployeeID = empTable.PersonnelID
inner join
tblPersonnel as mgrTable
on tblEmployeeProfile.ManagerID = mgrTable.PersonnelID
where EmployeeID = #EmployeeID

Related

why does calculation changes in order taken

why does this query miscalculates the colum for ordertaken?? is it about the groupings>
SELECT t2.employeeid, t1.firstname || ' ' || t1.lastname as fullname,
sum(t3.quantity*t4.price) as totalsales,
COUNT(t2.orderid) AS ordertaken, COUNT(DISTINCT t2.customerid) AS uniquecustomercount
from employees as t1
join orders as t2 on t2.employeeid = t1.employeeid
join order_details as t3 on t2.orderid = t3.orderid
join products as t4 on t4.productid = t3.productid
group by t2.employeeid, fullname
correct computation for column ordertaken
If I understand correctly, you need a distinct count for both counts:
SELECT
t2.employeeid,
t1.firstname || ' ' || t1.lastname AS fullname,
SUM(t3.quantity*t4.price) AS totalsales,
COUNT(DISTINCT t2.orderid) AS ordertaken,
COUNT(DISTINCT t2.customerid) AS uniquecustomercount
FROM employees AS t1
INNER JOIN orders AS t2 ON t2.employeeid = t1.employeeid
INNER JOIN order_details AS t3 ON t2.orderid = t3.orderid
INNER JOIN products AS t4 ON t4.productid = t3.productid
GROUP BY t2.employeeid, fullname;
The distinct counts are required on the counts from the orders table because the joins to order_details and products may duplicate a given order record, magnifying the count.

Convert a Postgres query into JPQL

I have the following query in Postgres:
SELECT *
from table1
LEFT OUTER JOIN table1.table2 ON table1.latest_id = table2.id
WHERE table1.table2.status = 0
AND table1.id NOT IN (
(SELECT id from table3 where userId = table2.user))
I do not have the ability to join table1 and table3 and I am stuck writing the subquery in a format JPA will understand - working with a spring boot app. Here is where I got so far in my repository class:
#Query("SELECT c FROM #{#entityName} c JOIN FETCH c.table2 WHERE c.table2.status = 0")
fun findByIdAndStatus(id: String): MyEntity
I have attempted at the subquery as follows, but with no joy - there is a clear syntax error I cannot wrap my head around:
#Query("SELECT c FROM #{#entityName} c JOIN FETCH c.table2 WHERE c.table2.status = 0" AND c.id NOT IN (" +
"SELECT * FROM Table3 WHERE userId = c.table2.user")
Can you help?
Thank you
Assuming:
your SQL query doesn't utilize any input arguments
table1 is mapped by MyEntity and table3 is mapped by Table3 entity
entity associated with table2 is mapped in MyEntity using latest_id join column
status is mapped as a number (i.e Long / Integer)
You can rewrite the query to following JPQL form:
#Query("SELECT t1 FROM MyEntity t1 "
+ "JOIN t1.table2 t2 "
+ "WHERE t2.status = 0 AND t1.id NOT IN ("
+ " SELECT t3.id from Table3 t3 "
+ " WHERE t3.userId = t2.user "
+ ")")
List<MyEntity> findMyEntities();

What is the proper syntax to alias a join that contains a subquery?

I am trying to alias a JOIN that has a subquery.
RIGHT OUTER JOIN
(
SELECT FieldA, FieldB
FROM Table1
JOIN Table2
ON Table1.WellId = Table2.WellId
) AS wi
AS MProd
ON Units.RS_Unit_Name = RTRIM(wi.RS_POOL) + '-' + wi.RS_Field
I get incorrect syntax near 'AS'...
wi is the alias FieldA & FieldB; How do I alias the RIGHT OUTER JOIN?
My original code was:
RIGHT OUTER JOIN TABLE1
AS MProd
ON Units.RS_Unit_Name = RTRIM(wi.RS_POOL) + '-' + wi.RS_Field
which worked fine. I replaced TABLE1 with a subquery which I did in the code sample. I just can't seem to figure out the proper syntax to set MProd as the alias.
The problem is this line of code:
AS wi AS MProd
This is not valid syntax. It can be AS wi or AS MProd, but not AS wi AS MProd.
This is valid:
RIGHT OUTER JOIN
(
SELECT FieldA, FieldB
FROM Table1
JOIN Table2 ON Table1.WellId = Table2.WellId
) AS MProd
ON Units.RS_Unit_Name = RTRIM(MProd.RS_POOL) + '-' + MProd.RS_Field ...
and so is this:
RIGHT OUTER JOIN
(
SELECT FieldA, FieldB
FROM Table1
JOIN Table2 ON Table1.WellId = Table2.WellId
) AS wi
ON Units.RS_Unit_Name = RTRIM(wi.RS_POOL) + '-' + wi.RS_Field ...

SQL Update query explanation

I would appreciate it if someone can explain me how the piece of code below works internally. For example, how the order of conditions is evaluated.
update br set ScannedId =
(
select top 1 Id from table1 sp (nolock)
inner loop join table2 cp (nolock) ON (sp.CPId = cp.CPID)
inner loop join table3 c (nolock) ON (cp.CID = c.CId and c.endDate >= sp.CreatedDate and c.startDate <= sp.CreatedDate ) `enter code here`
inner loop join table4 cc (nolock) ON (c.CChannelID =`enter code here` cc.CChannelID)
where (sp.UserId is null or sp.UserId = br.UserId)
and ((sp.Email = br.UserEmail)
or (sp.fName like br.UFName + '%' and sp.LName like br.ULName + '%' and sp.sHash = br.uHash)
or (sp.fName like br.UFName + '%' and sp.Addrs = br.UOAddrs and sp.ZC = br.UOZ and sp.sHash = br.uHash))
order by cc.Rank, c.Rank, cp.Rank, sp.EDate desc, sp.CreatedDate desc
)
from channelnewlogic br where userId = 3637217
Rows in channelnewlogic get their ScannedId column values updated according to the result of the inner select.

How do I join two tables with different column in SQL Server CE?

How can I joining two tables with different column in SQL Server CE?
I have two tables:
Table Schedule
+-----+----------+------+
+ ID + Name + Type +
+-----+----------+------+
+ 1 + A + 1 +
+ 2 + B + 1 +
+ 3 + C + 2 +
+-----+----------+------+
Table Description
+-----+--------------------+
+ ID + Description +
+-----+--------------------+
+ 1 + A1 - XXXXX +
+-----+--------------------+
And what I want to get is the table like:
+-----+----------+-----------------+
+ ID + Name + Description +
+-----+----------+-----------------+
+ 1 + A + A1 - XXXXX +
+ 2 + B + - +
+ 3 + C + - +
+-----+----------+-----------------+
Where the Description column should be filled in by - when the ID is not on the Description table.
I tried this code:
SELECT S.ID, D.Description
FROM Schedule AS S
INNER JOIN Description AS D
But resulted in:
+-----+----------+-----------------+
+ ID + Name + Description +
+-----+----------+-----------------+
+ 1 + A + A1 - XXXXX +
+ 2 + B + A1 - XXXXX +
+ 3 + C + A1 - XXXXX +
+-----+----------+-----------------+
And when I tried to give ON Clause:
SELECT S.ID, D.Description
FROM Schedule AS S
INNER JOIN Description AS D ON S.ID = D.ID
It just get the row where the ID is on the Description table, like:
+-----+----------+-----------------+
+ ID + Name + Description +
+-----+----------+-----------------+
+ 1 + A + A1 - XXXXX +
+-----+----------+-----------------+
How can I do that?
[UPDATE]
I tried this code and it works:
SELECT S.ID, S.Name, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D ON S.ID = D.ID
But now, how can I add a WHERE clause on it (pls see table SCHEDULE above)?
I tried:
SELECT S.ID, S.Name, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D ON S.ID = D.ID AND S.Type = '1'
But still get the whole rows.
LEFT OUTER JOIN in SQL Server CE
You need to use LEFT OUTER JOIN to join the tables Schedule and Description on the key field ID. Also, use COALESCE to replace NULL values in Description column with -
Script:
SELECT S.ID
, S.Name
, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D
ON S.ID = D.ID
Output:
Tested in Microsoft SQL Server CE version 4.0.8482.1
With WHERE clause
You need add the WHERE clause after the JOINs. If you are planning to having an ORDER BY, it should come after the WHERE clause.
Script:
SELECT S.ID
, S.Name
, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D
ON S.ID = D.ID
WHERE (S.Type = 1)
Output:
Tested in Microsoft SQL Server CE version 4.0.8482.1
You need LEFT OUTER JOIN.
SQLFiddle: http://sqlfiddle.com/#!3/7dccf/1
Query:
select s.ID, s.Name, Coalesce(d.description,'-') as description
from schedule s
left outer join description d on d.id = s.id
SELECT S.ID, D.Description
FROM Schedule AS S FULL OUTER JOIN Description AS D
ON S.ID = D.ID
INNER JOIN means select only rows that exist in both tables.
FULL OUTER JOIN means select rows as long as they exist in one table.
You need FULL OUTER JOIN...
You need to use an OUTER JOIN instead of INNER, and use IsNull or Coalesce to replace NULL values:
SELECT S.ID, Coalesce(D.Description , '-') AS Description
FROM Schedule AS S FULL OUTER JOIN Description AS D
ON S.ID = D.ID