Select records when 2 column's data will match - sql-server

I have two tables as shown below:
-----------------------
|EmpNo|Complaint |
-----------------------
|9091 |Change required|
|9092 |No change |
|9093 |Changes done |
-----------------------
Above table contains employee number and his complaints.
I have one another table which contains employee all kind of details as shown below.
-------------------------------
|EmpNo|EmailID |EmpBossNO|
-------------------------------
|9091 |abc#gmail.com|9092 |
|9092 |xyz#gmail.com|9093 |
|9093 |mno#gmail.com|9099 |
-------------------------------
Here, if Empno:9091 will raise any complain then a mail will send to his boss that the complain is raise by your employee and you have to accept it so I want to get EmailID of employee's boss and for that I want one SQL query. I tried the query shown here, but it doesn't work.
select EmpEmailID
from tblComplaint
inner join tblEmpMaster on tblEmpMaster.EmpNo = tblComplaint.EmpPSNo
where tblComplaint.EmpPSNo = tblEmpMaster.EmpBossNo
I want output like.. if complaint is raised by EmpNo:9091 then it will return EmailID of his boss which is xyz#gmail.com.

You are on the right track with a join between the tblComplaint and tblEmpMaster tables. But, you need an additional join to tblEmpMaster to bring in the boss' email for each employee complaint.
SELECT
c.EmpNo,
c.Complaint,
COALESCE(e2.EmailID, 'NA') AS boss_email
FROM tblComplaint c
INNER JOIN tblEmpMaster e1
ON c.EmpNo = e1.empNo
LEFT JOIN tblEmpMaster e2
ON e1.EmpBossNO = e2.EmpNo;
Demo
I used a left self join above, in case a given employee does not have a boss (e.g. for the highest ranking boss). In this case, I display NA for the boss email.

You should self join tblEmpMaster
select boss.EmpEmailID
from tblComplaint
inner join tblEmpMaster emp on emp.EmpNo = tblComplaint.EmpPSNo
inner join tblEmpMaster boss on boss.EmpNo = emp.EmpBossNO
where tblComplaint.EmpPSNo = 9091
DB Fiddle

you can even use sub queries to get the Email_Id of the boss as shown below
SELECT Email_Id
FROM EMP_Details
WHERE Emp_No IN (
SELECT Boss_Id
FROM Emp_Details) AND
Emp_No IN (
SELECT Emp_No
FROM Emp_Complaints)

Related

SQL Join that only returns records that are missing in other table

Consider two tables in a SQL Server database:
Order
OrderId | OrderType | etc...
Shipment
ShipmentId | OrderId | ShipType | etc..
I'm trying to write a select statement that returns OrderIds :
where Order.OrderType = 'EXCHANGE'
and there is no corresponding record in the Shipment table that has
Shipment.OrderId = Order.OrderId and Shipment.ShipType = 'BOX'
The reason for this is that depending on the OrderType, a BOX may or may not to be shipped to the customer. I want to grab all the OrderIds that are of OrderType = 'EXCHANGE' but have no corresponding BOX shipment so they can be forwarded to be shipped.
You can use not exists:
select o.*
from order o
where o.OrderType = 'EXCHANGE' and
not exists (select 1
from shipment s
where s.OrderId = o.OrderId and s.ShipType = 'BOX'
);
Note: As written this won't work because order is a SQL keyword and reserved word -- that makes it a very poor choice of table name (you can escape the name, although you do not in the question). I would suggest you call it something else, such as orders.
You could use LEFT JOIN.
SELECT
o.*
FROM Order o
LEFT JOIN Shipment s ON s.OrderId = o.OrderId AND s.ShipType = 'BOX'
WHERE
o.OrderType = 'EXCHANGE'
AND s.ShipmentId IS NULL

SQL query to get data from two rows connected by key

I have a question that seems very simple to me at first but I'm relatively new to SQL and I can't solve it.
I have two tables: 'Applicants' and 'Family Units'.
Applicants:
ApplicantID | FirstName
----------- | ----------
1 | John
2 | Mary
Family Units:
ApplicantID | UnitID| Note
1 | 10 | Member
2 | 10 | Mother
I need to bring in one table Applicant Name and Mother Name.
Mother applicantID should be determined by having same UnitID in Family Units table and Mother Note in the same table (and other details they are not relevant here).
I tried this query:
That obviously doesn't work correct, I get applicant name instead of applicant's mother's name.
Need you help, links to articles and explanations also will be great because I feel that I'm missing something very basic.
; with cte as
(
select fu.*,a.name from
FamilyUnit fu
join applicant a on a.id = fu.id
where type = 'Mother'
)
select a.id,a.name,c.name
from applicant a
join FamilyUnit fu on fu.id = a.id
join cte c on c.unit = fu.unit
where c.id <> a.id
Im not so sure if this is correct: just try it
select * from
(select * from #family_units where note = 'member') as a
left join
(select * from #family_units where note = 'mother') as b
on a.unitid = b.unitid
left join #applicant_table as c
on a.ApplicantID =c.ApplicantID
Test result:
1 10 Member 2 10 Mother 1 John

INNER JOIN + JOIN returning duplicating result

I have a SQL Server query that it trying to connect 3 tables. I am getting the results I need, but have a duplication issue.
table1 is the main record table. table2 is basically a user table. table3 is a lookup table that connects users to managers.
I need to connect one user to all the records connected to himself and any other users connected to his manager (or the people he manages, if a manager). All managers are users, and any user can 'own' a record on table1.
table3 connects userIDs on table2 to the userID of the manager also on table2.
table3 (lookup table)
id | altID
15 | 205
16 | 205
17 | 205
18 | 246
table2 (user table)
id | other_col
15 | abc
16 | def
17 | ggg
18 | hhh
205| yyy
246| zzz
table1 (record table)
id | record_data
15 | abc
16 | def
17 | ggg
18 | hhh
205| yyy
246| zzz
The user will put in their ID. So if id = 'XYZ'.
SELECT c.id, c.col, s.col2, s.col3
FROM table1 AS c
INNER JOIN table2 AS s
ON c.id = s.id
JOIN table3 AS p
ON c.id = p.id OR c.id = p.altID
WHERE
(p.id = 'XYZ'
OR p.altID = 'XYZ')
AND
(c.id = p.altID
OR c.id = p.id)
AND
NULLIF(LTRIM(RTRIM(c.column)), '') IS NOT null
This is giving me all the associated records (all the users that XYZ is related to). It is, however, including XYZ twice, and I cannot figure out why.
This is resolvable using DISTINCT(c.id) in the SELECT statement, but I am trying to understand why the duplication happens to begin with.
Here’s what I get when I work through the logic in the query:
The join from table1 (c) to table2 (s) is one-to one, as (s) contains a single row with the “name” for the Id in (c). No duplciation problems there.
You then join table1 (c) to table 3 (p), from the “owing” id in (c) to all rows in (p) for that id, for both user and manager columns. Thus, if the item in (c) is owned by a manager, you will get one or more hits, once for them as a user and once for each time they are a manager.
Leastways, that’s what I figure based solely on the code and the descriptions you provided.
If you want to show the relation USER - MANAGER defined in table3 one posible way is to join the lookup table (table3) again with the user table (to get the manager record).
SELECT c.id, s.other_col, p.altid, manager.other_col manager_name
FROM table1 c
JOIN table2 s
ON c.id = s.id
LEFT OUTER JOIN table3 p
ON c.id = p.id
LEFT OUTER JOIN table2 manager
ON p.altid = manager.id;
ID OTHER_COL ALTID MANAGER_NAME
---------- --------- ---------- ------------
17 ggg 205 yyy
16 def 205 yyy
15 abc 205 yyy
18 hhh 246 zzz
246 zzz
205 yyy
I'm using OUTER JOIN, that will show also users withou manager. INNER JOIN will suppress those records.

SELECT DISTINCT showing duplicate dates per customer email

I am trying to retrieve information for the past ten months, but am having a couple of errors. First, my query is getting data from as far back as 2013. Secondly, I am seeing duplicates in my results based on the PolEffDate field, like this:
EntityID | PolEffDate | EMail | CustNo | Producer | BusinessPhone
abcde-12345-fghij-67890 | 2013-09-24 | somewhere#email.com | 31000 | Bob Builder | 123-456-7890
abcde-12345-fghij-67890 | 2013-12-01 | somewhere#email.com | 31000 | Bob Builder | 123-456-7890
abcde-12345-fghij-67890 | 2014-09-24 | somewhere#email.com | 31000 | Bob Builder | 123-456-7890
Here is my SQL Query:
SELECT DISTINCT
CONVERT(VarChar(36), Customer.CustId) AS EntityID
, BasicPolInfo.PolEffDate, Customer.EMail, Customer.CustNo
, (isnull(Employee.Firstname + ' ','') + isnull(Employee.LastName,''))
AS Producer, Employee.BusFullPhone
FROM
Customer INNER JOIN BasicPolInfo ON Customer.CustId = BasicPolInfo.CustId INNER JOIN
Transaction ON BasicPolInfo.PolId = Transaction.PolId INNER JOIN
GeneralBranch ON Customer.GLBrnchCode = GeneralBranch.GLBrnchCode INNER JOIN
GeneralDepartment ON Customer.GLDeptCode = GeneralDepartment.GLDeptCode INNER JOIN
GeneralDivision ON Customer.GLDivCode = GeneralDivision.GLDivCode INNER JOIN
Employee ON BasicPolInfo.ExecCode = Employee.EmpCode
WHERE
BasicPolInfo.PolExpDate >= DATEADD(MONTH, -10,CONVERT(VARCHAR(11),GETDATE(),106))
AND BasicPolInfo.PolExpDate <= CONVERT(VARCHAR(11),GETDATE(),106)
AND Customer.Active = 'Y'
AND Customer.typeCust = 'P'
Thank you for the help. I will try my best to answer any questions.
Daniel, the duplication you are seeing is caused because you have multiple records in BasicPolInfo for each CustID value. You can confirm this by running the following query:
SELECT CustID, COUNT(*)
FROM BasicPolInfo
GROUP BY CustID
HAVING COUNT(*) > 1
Depending on your schema, this may not be an issue - after all, there is probably a perfectly legitimate reason for that! Multiple policies per Customer is my guess.
To resolve the duplication, I would recommend a GROUP BY with MIN() or MAX().
Your other issue, that of retrieving data from earlier dates, is because you are selecting the PolEffDate (presumably, policy effective date), but filtering the PolExpDate (presumably, policy expiration date). Which are you intending to use? Policies that have finished sometime in the last ten months could have started much earlier than that.
To resolve the wider date range, reference the same value in your SELECT and WHERE clauses.
Query below (using MAX() and PolExpDate):
SELECT
CONVERT(VarChar(36), Customer.CustId) AS EntityID,
MAX(BasicPolInfo.PolExpDate) AS PolExpDate, -- note that this is now PolExpDate
Customer.EMail,
Customer.CustNo,
(isnull(Employee.Firstname + ' ','') + isnull(Employee.LastName,'')) AS Producer,
Employee.BusFullPhone
FROM
Customer INNER JOIN
BasicPolInfo ON Customer.CustId = BasicPolInfo.CustId INNER JOIN
[Transaction] ON BasicPolInfo.PolId = [Transaction].PolId INNER JOIN
GeneralBranch ON Customer.GLBrnchCode = GeneralBranch.GLBrnchCode INNER JOIN
GeneralDepartment ON Customer.GLDeptCode = GeneralDepartment.GLDeptCode INNER JOIN
GeneralDivision ON Customer.GLDivCode = GeneralDivision.GLDivCode INNER JOIN
Employee ON BasicPolInfo.ExecCode = Employee.EmpCode
WHERE
BasicPolInfo.PolExpDate >= DATEADD(MONTH, -10,CONVERT(VARCHAR(11),GETDATE(),106))
AND BasicPolInfo.PolExpDate <= CONVERT(VARCHAR(11),GETDATE(),106)
AND Customer.Active = 'Y'
AND Customer.typeCust = 'P'
GROUP BY
CONVERT(VarChar(36), Customer.CustId),
Customer.EMail,
Customer.CustNo,
(isnull(Employee.Firstname + ' ','') + isnull(Employee.LastName,'')),
Employee.BusFullPhone

SQL Server query result needs to give different values in two columns of the same name from the same source table

Not sure if my title makes sense but here's what I'm trying to do. I'm trying to write a query that produces the same column twice in the result but the first column will have different values than the second column.
For example, in short, Table provider_mstr contains the columns national_provider_id, provider_id, and description. Table appointments contains the columns person_id and rendering_provider_id. Table person contains the columns primarycare_prov_name and primarycare_prov_id. So I'm looking for the result to look like this:
**primarycare_prov_name** **national_provider_ip** **description** **national_provider_id**
John Doe 12345 Rick Smith 56789
Jane Doe 25832 Barb Johnson 82473
...
So I'm wanting the national_provider_id for the primarycare_prov_name in the first national_provider_id column but the national_provider_id of the rendering_provider_id (description) in the second national_provider_id column.
Here is my full code:
select
person.person_nbr,
person.first_name,
person.middle_name,
person.last_name,
person.date_of_birth,
person.sex,
person.email_address,
person.address_line_1,
person.address_line_2,
person.city,
person.state,
person.zip,
person.home_phone,
person.day_phone,
person.alt_phone,
person.primarycare_prov_name,
provider_mstr.national_provider_id,
appointments.appt_date,
appointments.begintime,
appointments.appt_type,
appointments.appt_nbr,
appointments.details,
appointments.rendering_provider_id,
location_mstr.location_name,
provider_mstr.description,
provider_mstr.national_provider_id,
charges.cpt4_code_id
FROM person
LEFT JOIN patient
ON person.person_id=patient.person_id
LEFT JOIN appointments
ON person.person_id=appointments.person_id
LEFT JOIN location_mstr
ON appointments.location_id=location_mstr.location_id
LEFT JOIN provider_mstr
ON person.primarycare_prov_id = provider_mstr.provider_id
LEFT JOIN charges
ON person.person_id = charges.person_id
WHERE .....
So what do I need to do to get that to happen?
You need to join to the provider_mstr table twice. Once for rendering provider second time for primary care provider:
SELECT
person.primarycare_prov_name,
primarycare_provider.national_provider_id,
rendering_provider.description,
rendering_provider.national_provider_id
FROM person
LEFT JOIN appointments
ON person.person_id=appointments.person_id
LEFT JOIN provider_mstr rendering_provider
ON rendering_provider.provider_id = appointment.rendering_provider_id
LEFT JOIN provider_mstr primarycare_provider
ON primarycare_provider.provider_id = person.primarycare_prov_id

Resources