Reputation: 71
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 :)
Upvotes: 0
Views: 122
Reputation: 127543
No you can not, you are using D
, E
, and F
in your result set so you must join those tables. You could only remove them if you removed things like D.FullName AS CallOpenedBy
and E.FullName AS
and
EngineerNameF.FullName AS CallClosedBy
from 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.CallClosedBy
has not been assigned to a value in F.UserProID
the row will be excluded from the result.
You should be using LEFT OUTER JOIN
for 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
Select B.BranchName, C.Name AS CustomerName,IsNull(D.FullName, '(Not Assigned)') AS CallOpenedBy,
A.CallOpenTime,A.CallMode, A.CallType,A.ReportedBy, A.ReportedVia, A.ReportedProblem,
A.MaterialsReceived, A.MisComments,A.CallPriority,A.EstimatedAmount,IsNull(E.FullName, '(Not Assigned)') AS
EngineerName, A.ActionTaken, A.CallClosedTime,IsNull(F.FullName, '(Not Assigned)') 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
LEFT OUTER JOIN TblUserProfiles D ON A.CallOpenedBy = D.UserProID
LEFT OUTER JOIN TblUserProfiles E ON A.Engineer = E.UserProID
LEFT OUTER JOIN TblUserProfiles F ON A.CallClosedBy = F.UserProID
Now if the value is NULL
or the record does not exist in the destination table it will say (Not Assigned)
in the output instead of excluding the row.
Upvotes: 3