Query shows each row twice - sql

It shows each row twice... I wrote it to pick some rows from different tables, it shows what I want but it shows those rows twice, each. why ?
SELECT
tbluser.fullname, tbluser.email, tblJobAdv.advtitle, tblPersonalInfo.country,
tblPersonalInfo.city, tblJobOffer.digitalsignature
FROM
tblUser
LEFT JOIN
tblPersonalInfo ON tblUser.userid = tblPersonalInfo.userid
LEFT JOIN
tblApplication ON tblApplication.userid = tblUser.userid
LEFT JOIN
tblJobAdv ON tblJobAdv.advid = tblApplication.advid
LEFT JOIN
tblJobOffer ON tblUser.userid = tblJobOffer.userid
WHERE
tblJobAdv.userId IN (SELECT userid FROM tblUser WHERE email = 'h#y.com')

It shows duplicate records because you are joining along different dimensions. If I had to guess, based on the table names, users are applying for multiple jobs.
A quick and easy fix is to do select distinct.
Actually, you should check your underlying tables to be sure there are no duplicates in them. I am suspicious about the Application table. I think there might be multiple applications for a given user.

using 'group by' or 'distinct' makes your query slow and inefficient.
I think you would better finding duplicated rows from other tables like tblJobAdv,
and give some more 'where condition' to those tables.
SELECT tbluser.fullname, tbluser.email, tblJobAdv.advtitle, tblPersonalInfo.country,
tblPersonalInfo.city, tblJobOffer.digitalsignature
FROM
tblUser
LEFT JOIN
tblPersonalInfo ON tblUser.userid = tblPersonalInfo.userid
LEFT JOIN
tblApplication ON tblApplication.userid = tblUser.userid
LEFT JOIN
tblJobAdv
ON tblJobAdv.advid = tblApplication.advid
AND tblJobAdv.isUsable = 'Usable' /* some more where condition example */
LEFT JOIN
tblJobOffer ON tblUser.userid = tblJobOffer.userid
WHERE
tblJobAdv.userId IN (SELECT userid FROM tblUser WHERE email = 'h#y.com')

Please try select distinct to avoid duplicate records

You just need to group the records or distinct will do (remove duplicates),
Select distinct tbluser.fullname, tbluser.email, tblJobAdv.advtitle, tblPersonalInfo.country,
tblPersonalInfo.city, tblJobOffer.digitalsignature
from tblUser
left join tblPersonalInfo
ON tblUser.userid = tblPersonalInfo.userid
left join tblApplication
On tblApplication.userid = tblUser.userid
left join tblJobAdv
On tblJobAdv.advid = tblApplication.advid
left join tblJobOffer
On tblUser.userid = tblJobOffer.userid
where tblJobAdv.userId IN (select userid from tblUser where email = 'h#y.com')

Related

Get all the values from the first left table but when two left joins used its restricting the values from first table

I am trying to get all the values from the first left table but when I use two left joins its restricting the values from first table.
I used the below query
SELECT P.person_id, TS.Task_Id, TS.skill
FROM Person P
LEFT JOIN Person_Skill PS ON P.person_id = PS.person_id
LEFT JOIN Task_Skill TS ON PS.Skill = TS.Skill
WHERE ts.task_id = 245
I need all the person id from person table.
Just move the condition on the left joined table from the where clause to the on clause of the join:
select p.person_id, ts.task_id, ts.skill
from person p
left join person_skill ps
on p.person_id = ps.person_id
left join task_skill ts
on ps.skill = ts.skill
and ts.task_id = 245 --> here
Rationale: conditions in the where clause are mandatory. If there is no match in ts, then condition ts.task_id = 245 cannot be satisfied, since ts.task_id is null.
Use the filter condition in a sub query instead of using it as a global filter outside. This should give you the output that you desire.
SELECT P.person_id,TS.Task_Id,TS.skill FROM Person P
LEFT JOIN Person_Skill PS
ON P.person_id=PS.person_id
LEFT JOIN
(Select * from Task_Skill where task_id = 245) TS
ON PS.Skill=TS.Skill;

why I get different number of records when using LEFT JOIN

I need to join many to many relationship. In order to do that I am using
LEFT OUTER JOIN
(SELECT
SICCode, QuoteID
FROM
NetRate_Quote_Insur_Quote_Busin
WHERE
QuoteID IN
(SELECT DISTINCT QuoteID
FROM NetRate_Quote_Insur_Quote_Busin)) nr ON nr.QuoteID = tblQuotes.QuoteID
The goal is to bring the column SICCode. For that, I am using DISTINCT statement to make relationship many to one. But for some reason I got different number of records.
The last LEFT OUTER JOIN is the one that I am stuck with
Full query looks like this:
SELECT
MONTH(INV.EffectiveDate) AS Effective_Month,
tblQuotes.PolicyNumber,
YEAR(INV.EffectiveDate) AS Effective_Year,
INV.EffectiveDate,
INV.[InvoiceDate] as [Billed Date],
tblQuotes.ExpirationDate as [Policy Expiration Date],
INV.DueDate,
dbo.tblFin_InvoiceDetails.AmtBilled AS Written
FROM
tblClientOffices
INNER JOIN
tblInsureds (NOLOCK)
INNER JOIN
tblFin_Invoices INV
INNER JOIN
tblFin_InvoiceDetails ON INV.InvoiceNum = dbo.tblFin_InvoiceDetails.InvoiceNum
INNER JOIN
tblCompanyLines (NOLOCK) ON dbo.tblFin_InvoiceDetails.CompanyLineGuid = dbo.tblCompanyLines.CompanyLineGUID
INNER JOIN
lstLines (NOLOCK) ON dbo.tblCompanyLines.LineGUID = dbo.lstLines.LineGUID
AND dbo.tblCompanyLines.LineGUID = dbo.lstLines.LineGUID
INNER JOIN
tblProducerLocations (NOLOCK) ON INV.ProducerLocationGUID = tblProducerLocations.ProducerLocationGUID
ON tblInsureds.InsuredGUID = INV.InsuredGUID
INNER JOIN
tblQuotes (NOLOCK) ON INV.QuoteID = tblQuotes.QuoteID
AND INV.QuoteControlNum = tblQuotes.ControlNo
INNER JOIN
lstPolicyTypes (NOLOCK) ON tblQuotes.PolicyTypeID = lstPolicyTypes.PolicyTypeID
INNER JOIN
tblSubmissionGroup (NOLOCK) ON tblQuotes.SubmissionGroupGuid = tblSubmissionGroup.SubmissionGroupGUID
INNER JOIN
tblCompanyLocations (NOLOCK) ON tblQuotes.CompanyLocationGuid = tblCompanyLocations.CompanyLocationGUID
INNER JOIN
tblUsers (NOLOCK) ON INV.UnderwriterUserGUID = tblUsers.UserGUID
ON tblClientOffices.OfficeGUID = tblQuotes.IssuingLocationGuid
LEFT OUTER JOIN
tblUsers tblUsers_1 (NOLOCK) ON tblSubmissionGroup.InHouseProducerUserGuid = tblUsers_1.UserGUID
LEFT OUTER JOIN
(SELECT SICCode, QuoteID
FROM NetRate_Quote_Insur_Quote_Busin
WHERE QuoteID IN
(SELECT DISTINCT QuoteID
FROM NetRate_Quote_Insur_Quote_Busin)) nr ON nr.QuoteID = tblQuotes.QuoteID
WHERE
(tblInsureds.TestInsured = 0)
AND (INV.Failed = 0)
AND (tblFin_InvoiceDetails.ChargeType = 'p')
ORDER BY
YEAR(INV.EffectiveDate),
MONTH(INV.EffectiveDate),
lstLines.LineID
What would be the trick to bring Column SICCode and keep the same number of records?
I also tried to do this:
LEFT OUTER JOIN NetRate_Quote_Insur_Quote_Busin nr ON nr.QuoteID =
(
SELECT distinct QuoteID from NetRate_Quote_Insur_Quote_Busin
where QuoteID =tblQuotes.QuoteID
)
But it gives me more records than it should be
Also tried this one:
LEFT OUTER JOIN
( SELECT TOP 1 SICCode, QuoteID
FROM NetRate_Quote_Insur_Quote_Busin
WHERE QuoteID IN
(SELECT DISTINCT QuoteID
FROM NetRate_Quote_Insur_Quote_Busin)order by QuoteID desc ) nr ON nr.QuoteID = tblQuotes.QuoteID
But doesnt bring me any SICCode
DISTINCT will not change a many to many relationship to a many to one. It looks like your data has many SICCode values to one QuoteID which is why you getting higher record counts.
You could use a window function like Rank, but this is an arbitrary selection.
You could try to pivot/unpivot the SICCode column, but that would give you 1 column for each possible value, which would not work if you have a large number of unique values in the column.
A final option is to create a new table which has a QuoteID column and a SICCodes column, then populate it withSICCodes being a comma seperated list of the codes.
In conclusion, there is no easy way to change a many to many relationship to a many to one relationship unless you are willing to lose data or there are only a few values.

returned no of rows different on left join

i have two sql query in one of them i perform left outer join, both should return same no of records but returned no of rows are different in both the sql queries
select Txn.txnRecNo
from Txn
inner join Person on Txn.uwId = Person.personId
full outer join TxnInsured on Txn.txnRecNo = TxnInsured.txnRecNo
left join TxnAdditionalInsured on Txn.txnRecNo = TxnAdditionalInsured.txnRecNo
where Txn.visibleFlag=1
and Txn.workingCopy=1
returned 20 records
select Txn.txnRecNo
from Txn
inner join Person on Txn.uwId = Person.personId
full outer join TxnInsured on Txn.txnRecNo = TxnInsured.txnRecNo
where Txn.visibleFlag=1
and Txn.workingCopy=1
returned 15 records
I suspect that the TxnAdditionalInsured table have duplicate records. use distinct
select distinct Txn.txnRecNo
from Txn
inner join Person on Txn.uwId = Person.personId
full outer join TxnInsured on Txn.txnRecNo = TxnInsured.txnRecNo
left join TxnAdditionalInsured on Txn.txnRecNo = TxnAdditionalInsured.txnRecNo
where Txn.visibleFlag=1
and Txn.workingCopy=1
A left join will produce all rows from the left side of the join at least once in the result set.
But if your join conditions are such that there are multiple rows from the right side that match a particular row on the left, that left row will appear multiple times in the result (as many times as it is matched with a right row).
So, if the results are unexpected, your join criteria aren't are strict as they need to be or you do not understand your data as well as you thought you did.
Unlike the other answers, I would not suggest just adding distinct - I'd suggest you investigate your data and determine whether your ON clause needs strengthening or if your data is in fact incorrect. Adding distinct to "make the results look right" is usually a poor decision - prefer to investigate and get the correct query written.
Try this:
select distinct Txn.txnRecNo --> added distinct here
from Txn
inner join Person on Txn.uwId = Person.personId
full outer join TxnInsured on Txn.txnRecNo = TxnInsured.txnRecNo
left join TxnAdditionalInsured on Txn.txnRecNo = TxnAdditionalInsured.txnRecNo
where Txn.visibleFlag=1
and Txn.workingCopy=1

Joining multiple tables to one table in sql

I have a rather complex (well for me) sql query happening and I am having trouble with some concepts.
I have the following sql on a webpage that i am building
SELECT
[dbo].[Enrolment].[_identity], [dbo].[Enrolment].CommencementDate,
[dbo].[Enrolment].CompletionDate, [dbo].[Enrolment].enrolmentDate,
[dbo].[Course].name coursename, [dbo].[Course].Identifier as QUALcode,
[dbo].[Person].givenName, [dbo].[Person].Surname,[dbo].[Employer].name as empname,
[dbo].[Employer].Address1,[dbo].[Employer].Suburb,[dbo].[Employer].Phone,
[dbo].[Employer].PostCode,[dbo].[EnrolmentStatus].name as enrolname,
[dbo].[Student].identifier,[dbo].[Student].person,[dbo].[Contact].person as CONTACTid
FROM
(((([dbo].[Enrolment]
LEFT JOIN
[dbo].[Course] ON [dbo].[Enrolment].course = [dbo].[Course].[_identity])
LEFT JOIN
[dbo].[Employer] ON [dbo].[Enrolment].employer = [dbo].[Employer].[_identity])
LEFT JOIN
[dbo].[EnrolmentStatus] ON [dbo].[Enrolment].status = [dbo].[EnrolmentStatus].[_identity])
LEFT JOIN
[dbo].[Student] ON [dbo].[Enrolment].student = [dbo].[Student].[_identity])
LEFT JOIN
[dbo].[Person] ON [dbo].[Student].person = [dbo].[Person].[_identity]
LEFT JOIN
[dbo].[Contact] ON [dbo].[Employer].[_identity] = [dbo].[Contact].employer
WHERE
(([dbo].[EnrolmentStatus].name) = 'training'
OR
([dbo].[EnrolmentStatus].name) = 'enrolled')
This is working fine but what I would like to do is join to the [dbo].[Person] table again but this time joining from another table so the code I effectively need to patch into the above statement is
LEFT JOIN
[dbo].[Trainer] ON [dbo].[Enrolment].Trainer = [dbo].[Trainer].[_identity])
LEFT JOIN
[dbo].[Person] ON [dbo].[Trainer].person = [dbo].[Person].[_identity]
I then need to be able to get from the person table the name of the student and the name of the trainer, so I need 2 records from the person table for every record from the Enrolment table, the fields I need from the person table are the same for both trainer and student in that I am trying to get the given name and surname for both.
Any help or pointers would be most appreciated.
You have to just use replace your from clause with this. You have to just first use the Trainer table join, then Person table, then use the AND keyword to use multiple mapping with single table
FROM (((([dbo].[Enrolment]
LEFT JOIN [dbo].[Course] ON [dbo].[Enrolment].course = [dbo].[Course].[_identity])
LEFT JOIN [dbo].[Employer] ON [dbo].[Enrolment].employer = [dbo].[Employer].[_identity])
LEFT JOIN [dbo].[EnrolmentStatus] ON [dbo].[Enrolment].status = [dbo].[EnrolmentStatus].[_identity])
LEFT JOIN [dbo].[Student] ON [dbo].[Enrolment].student = [dbo].[Student].[_identity])
LEFT JOIN [dbo].[Trainer] ON [dbo].[Enrolment].Trainer = [dbo].[Trainer].[_identity])
LEFT JOIN [dbo].[Person] ON [dbo].[Student].person = [dbo].[Person].[_identity]
AND [dbo].[Trainer].person = [dbo].[Person].[_identity]
LEFT JOIN [dbo].[Contact] ON [dbo].[Employer].[_identity] = [dbo].[Contact].employer
Use aliasing like this..
LEFT JOIN [dbo].[Trainer] ON [dbo].[Enrolment].Trainer = [dbo].[Trainer].[_identity])
LEFT JOIN [dbo].[Person] AS p ON [dbo].[Trainer].person = p.[_identity]
If I get your question right - what you are trying to do is to join the same table twice in your SQL. You have one table Person which has both student and trainer information and you want to see their details side by side in your result set. So you need to join Person once with Student and another time with Trainer
To do this - you will have to join Person table together. Give your tables an alias like the other answers have suggested. Then your FROM clause can look like this -
FROM (((([dbo].[Enrolment]
LEFT JOIN [dbo].[Course] ON [dbo].[Enrolment].course = [dbo].[Course].[_identity])
LEFT JOIN [dbo].[Employer] ON [dbo].[Enrolment].employer = [dbo].[Employer].[_identity])
LEFT JOIN [dbo].[EnrolmentStatus] ON [dbo].[Enrolment].status = [dbo].[EnrolmentStatus].[_identity])
LEFT JOIN [dbo].[Student] ON [dbo].[Enrolment].student = [dbo].[Student].[_identity])
LEFT JOIN [dbo].[Person] P1 ON [dbo].[Student].person = P1.[_identity]
LEFT JOIN [dbo].[Contact] ON [dbo].[Employer].[_identity] = [dbo].[Contact].employer
LEFT JOIN [dbo].[Trainer] ON [dbo].[Enrolment].Trainer = [dbo].[Trainer].[_identity])
LEFT JOIN [dbo].[Person] P2 ON [dbo].[Trainer].person = P2.[_identity]
....
....
Here P1 and P2 are two aliases for [Person]

Joining multiple tables and getting multiple attributes from one of them

I'm trying to join multiple tables together for building a report. The report lists a course, revisions made to it, and who requested, made and approved the revisions.
Under requested, made an approved, the values are employee numbers. I'm trying to join my innerjoined table above, with the Employee table so I can list the names (not just employee numbers) of those that requested, made and approved revisions.
This is what I have which I know is totally wrong.
SELECT *
FROM Courses
INNER JOIN CourseRevisions ON CourseRevisions.PELID = Courses.PELID
INNER JOIN CourseGroups ON CourseGroups.CourseGroupID = Courses.CourseGroupID
INNER JOIN [dbo].[OPG_Employees] ON OPG_Employees.EmployeeID = CourseRevisions.UpdatedBy
AND OPG_Employees.EmployeeID = CourseRevisions.ApprovedBy
AND OPG_Employees.EmployeeID = CourseRevisions.RequestedBy
This only returns a single result which just happens to have the same employee ID listed for all 3 (Requested, Approved and Updated)
How would i get it so I can get the table result for individual employees in each?
You have to join to the OPG_Employees table once for each field, i.e. 3 times in the example above. One INNER JOIN to it for UpdatedBy, one INNER JOIN for ApprovedBy, one INNER JOIN for RequestedBy.
Something like so:
SELECT *
FROM Courses
INNER JOIN CourseRevisions ON CourseRevisions.PELID = Courses.PELID
INNER JOIN CourseGroups ON CourseGroups.CourseGroupID = Courses.CourseGroupID
INNER JOIN [dbo].[OPG_Employees] empUpdatedBy ON empUpdatedBy.EmployeeID = CourseRevisions.UpdatedBy
INNER JOIN [dbo].[OPG_Employees] empApprovedBy ON empApprovedBy.EmployeeID = CourseRevisions.ApprovedBy
INNER JOIN [dbo].[OPG_Employees] empRequestedBy ON empRequestedBy.EmployeeID = CourseRevisions.RequestedBy
You need a separate join for each employee being referenced:
SELECT *
FROM Courses INNER JOIN
CourseRevisions
ON CourseRevisions.PELID = Courses.PELID INNER JOIN
CourseGroups
ON CourseGroups.CourseGroupID = Courses.CourseGroupID INNER JOIN
[dbo].[OPG_Employees] UpdateEmp
ON UpdateEmp.EmployeeID = CourseRevisions.UpdatedBy INNER JOIN
[dbo].[OPG_Employees] ApprovedEmp
on OPG_ApprovedEmp.EmployeeID = CourseRevisions.ApprovedBy INNER JOIN
[dbo].[OPG_Employees] RequestedEmp
on RequestedEmp.EmployeeID = CourseRevisions.RequestedBy
Your original formulation required that all three ids be exactly the same.