I have this query below, its working fine, and I’m getting what I need. All I need to know is, is this right way to write this query as this or is there any way to shorten it?
I have 4 tables, 1st has branch information, 2nd has customer information, 3rd has engineer information, 4th has service calls information.
In service calls table, 3 columns match with 3 different engineer names
Here is the query
SELECT
B.BranchName, C.Name AS CustomerName,D.FullName AS CallOpenedBy,
A.CallOpenTime, A.CallMode, A.CallType, A.ReportedBy,
A.ReportedVia, A.ReportedProblem,
A.MaterialsReceived, A.MisComments, A.CallPriority, A.EstimatedAmount,
E.FullName AS EngineerName,
A.ActionTaken, A.CallClosedTime,
F.FullName AS CallClosedBy, A.Status,
A.Amount
FROM
TblServiceCalls A
INNER JOIN
TblBranchInfo B ON A.BranchID = B.BranchID
INNER JOIN
TblMainMaster C ON A.MasterID = C.MasterID
INNER JOIN
TblUserProfiles D ON A.CallOpenedBy = D.UserProID
INNER JOIN
TblUserProfiles E ON A.Engineer = E.UserProID
INNER JOIN
TblUserProfiles F ON A.CallClosedBy = F.UserProID
Can I shorten the query in last 3 lines? Thanks you guys in advance 🙂
No you can not, you are using
D,E, andFin your result set so you must join those tables. You could only remove them if you removed things likeD.FullName AS CallOpenedByandE.FullName ASandEngineerName
F.FullName AS CallClosedByfrom your result.As a side note (and the I bet the original reason you asked this question), but if a call has not been closed yet and
A.CallClosedByhas not been assigned to a value inF.UserProIDthe row will be excluded from the result.You should be using
LEFT OUTER JOINfor those 3 tables if any of the 3 columns they link on may not have a corresponding record in the destination table or could be null.Here is how I would do it
Now if the value is
NULLor the record does not exist in the destination table it will say(Not Assigned)in the output instead of excluding the row.