Conditional join if values exist join table - sql

I have a table named level_2_tags if the user has selected a level two tag i want the it to join with another table via inner join else I want it to join in a left join
IF RLT ID EXISTS BELOW METHOD
SELECT RMC.* INTO #TTEMP
FROM #TRestrictedMainCatagory RMC
JOIN #TRestrictedAssetType RAT
ON RMC.ID = RAT.ID
JOIN #TRestrictedLevelTwo RLT
ON RLT.ID=RAT.ID
ELSE
SELECT RMC.* INTO #TTEMP
FROM #TRestrictedMainCatagory RMC
JOIN #TRestrictedAssetType RAT
ON RMC.ID = RAT.ID
LEFT OUTER JOIN #TRestrictedLevelTwo RLT
ON RLT.ID=RAT.ID
please help me to resolve this matter

Related

Is it possible to have multiple joins between two tables in stored procedure?

I have two tables, "Booking" and "City". CityName field is primary key in City table and I have used it as foreign key for two columns "SourceCity" and "DestinationCity" in Booking table. I want to create a stored procedure to select all existing data from the Booking table for creating a view list, for which I have written the following.
SELECT [dbo].[Booking].[BookingID],
[dbo].[Booking].[CustomerName],
[dbo].[City].[CityName],
[dbo].[City].[CityName],
[dbo].[Booking].[StartingDate],
[dbo].[Booking].[EndingDate],
[dbo].[Car].[LicensePlateNumber],
[dbo].[Driver].[DriverName],
[dbo].[Booking].[AdvanceTaken],
[dbo].[Booking].[PendingPayment],
[dbo].[Booking].[TotalRent],
[dbo].[Booking].[BookingDate],
[dbo].[Booking].[IDProof]
FROM [dbo].[Booking]
**LEFT OUTER JOIN [dbo].[City]
ON [dbo].[Booking].[SourceCity] = [dbo].[City].[CityName]
AND [dbo].[Booking].[DestinationCity] = [dbo].[City].[CityName]**
LEFT OUTER JOIN [dbo].[Driver]
ON [dbo].[Driver].[DriverID] = [dbo].[Booking].[DriverAllotted]
LEFT OUTER JOIN [dbo].[Car]
ON [dbo].[Car].[CarID] = [dbo].[Booking].[CarAllotted]
ORDER BY [dbo].[Booking].[BookingID]
I am not sure if it is possible to do the following
LEFT OUTER JOIN [dbo].[City]
ON [dbo].[Booking].[SourceCity] = [dbo].[City].[CityName]
AND [dbo].[Booking].[DestinationCity] = [dbo].[City].[CityName]
I guess you need a different JOIN
FROM [dbo].[Booking] as booking
LEFT OUTER JOIN [dbo].[City] as source_city
ON booking.[SourceCity] = source_city.[CityName]
LEFT OUTER JOIN [dbo].[City] as destination_city
ON booking.[DestinationCity] = destination_city.[CityName]
....
Yes it is possible, you just need to use a different table alias. Beyond referencing the same table twice, table aliases can make your code look a lot cleaner, e.g.
SELECT b.CustomerName,
sc.CityName AS SourceCity,
dc.CityName AS DestinationCity,
b.StartingDate,
b.EndingDate,
c.LicensePlateNumber,
d.DriverName,
b.AdvanceTaken,
b.PendingPayment,
b.TotalRent,
b.BookingDate,
b.IDProof
FROM dbo.Booking AS b
LEFT OUTER JOIN dbo.City AS sc
ON sc.CityName= b.SourceCity
LEFT OUTER JOIN dbo.City AS dc -- Different Alias here
ON dc.CityName = b.DestinationCity
LEFT OUTER JOIN dbo.Driver AS d
ON d.DriverID = b.DriverAllotted
LEFT OUTER JOIN dbo.Car AS c
ON c.CarID = b.CarAllotted
ORDER BY
b.BookingID;
I appreciate that cleaner is somewhat subjective, but I would be astonished if anyone found this harder to read than your original query

How to join two tables that have a common field in third table?

How to join two tables that have a common field in third table?
E.g: Table A has RoleId, role description and Table B has AccessId,Access description.Table C has RoleAccessID,roleid, accessid. I need to display role description and their access description.Please let me know how to achieve this.
You can Try this below logic for your purpose-
SELECT A.role_description, B.access_description
FROM TABLE_A A
INNER JOIN TABLE_C C ON A.RoleId = C.RoleId
INNER JOIN TABLE_B B ON C.AccessId = B.AccessId
try this
SELECT
role.RoleID,
role.Role_Description,
ac.AccessId,
ac.Access_Description
FROM tblRole role
INNER JOIN tblRoleAccessInfo rac ON A.RoleId = C.RoleId
INNER JOIN tblAccessInfo ac ON C.AccessId = B.AccessId

Outer Join and Inner Join

I used inner join and outer join the following query. When executing this query I get duplicate records. How can I get unique results?
Select *
From DeliveryOrderMaster
Inner Join DeliveryOrder ON DeliveryOrderMaster.VoucherNo = DeliveryOrder.DONo
Inner Join Customer ON DeliveryOrderMaster.Code = Customer.ar_code
Left Outer Join tblbatchSerialNos On DeliveryOrder.DoNo = tblbatchSerialNos.VoucherNo And DeliveryOrder.StockCode = tblbatchSerialNos.ProductCode
Where DeliveryOrderMaster.VoucherNo= 'DO01304'
ORDER BY DeliveryOrder.DoNo ASC,DeliveryOrder.ID ASC
The problem there arent inner or left join. The problem can be the type of table. Are you sure that you have used the correct key to Connect table? Can you give an example of wath return the query?

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]

Query to Sum Numbers Based on Location (State)

I'm trying to write a query that will summarize all of the procedures performed during the calendar year 2013, whether the event happened on a mobile drive or at a fixed site within a particular state.
Every Drive is Unique and will either occur at a Fixed Site (CenterID) or on a Mobile Site, which are associated with Accounts (AccountID). My query looks like this:
select sum(proceduresperformed), sum(productscollected)
from DriveProjectionAndCollectedTotals DPaCT
inner join rpt_DriveMaster DM on DPaCT.DriveID=DM.DriveID
left outer join rpt_Accounts Acct on DM.AccountID=Acct.AccountID
left outer join rpt_CenterDetail CD on DM.CenterID=CD.CenterID
inner join rpt_AddressDetail AD on Acct.AccountID=AD.AccountID
inner join rpt_AddressDetail AD2 on CD.CenterID=AD2.CenterID
where AD.State='FL'
or AD2.State='FL'
and Year(DM.FromDateTime)=2013
But these numbers are really high and incorrect. So what I did was remove one of the joins (either the Account or the CenterDetail) and run the query twice to get numbers that look much more in line with what is expected:
select sum(proceduresperformed), sum(productscollected)
from DriveProjectionAndCollectedTotals DPaCT
inner join rpt_DriveMaster DM on DPaCT.DriveID=DM.DriveID
left outer join rpt_Accounts Acct on DM.AccountID=Acct.AccountID
--left outer join rpt_CenterDetail CD on DM.CenterID=CD.CenterID
inner join rpt_AddressDetail AD on Acct.AccountID=AD.AccountID
--inner join rpt_AddressDetail AD2 on CD.CenterID=AD2.CenterID
where AD.State='FL'
--or AD2.State='FL'
and Year(DM.FromDateTime)=2013
How can I fix the original query to summarize the two columns in a way that does not basically triple the expected value?
The original query returns:
And running the query with Accounts and Centers separately:
I went back and used a UNION statement to give me the correct answer:
select sum(procperf) as 'Procedures Performed'
from (
select sum(proceduresperformed) as procperf
from DriveProjectionAndCollectedTotals DPaCT
inner join rpt_DriveMaster DM on DPaCT.DriveID=DM.DriveID
left outer join rpt_Accounts Acct on DM.AccountID=Acct.AccountID
inner join rpt_AddressDetail AD on Acct.AccountID=AD.AccountID
where AD.State='FL'
and Year(DM.FromDateTime)=2013
UNION
select sum(proceduresperformed) as procperf
from DriveProjectionAndCollectedTotals DPaCT
inner join rpt_DriveMaster DM on DPaCT.DriveID=DM.DriveID
left outer join rpt_CenterDetail CD on DM.CenterID=CD.CenterID
inner join rpt_AddressDetail AD2 on CD.CenterID=AD2.CenterID
where AD2.State='FL'
and Year(DM.FromDateTime)=2013
) as a;