How to join a sub-query to - sql

Hey guys I have this report that i am working on. It has multiple Columns and in between those columns are some Left joins. so my question is, how do i add a left join to the query?
Declare #asofdate smalldatetime
Set #asofdate = '2017-08-24'
SELECT
OCCONR as [Company Number],
OCCMNR as [Claim Number], --CMOCUR db)
OCEXCD as [Claim Counsel], ---(CMOCUR db)
DATEFROMPARTS(OCEFCN*100+OCEFYY,OCEFMM,OCEFDD) as [Policy Effective Date], -- (CMOCUR db)
iif([True CAT Nbr] is null, OCCTCD, [True CAT Nbr]) as [CAT Code], ---(Check Comment 1)
iif(LSCMNT is null,'', LSCMNT) as [NOA Comments], --- (Check Comemnt 2)
concat([First_Name],' ',[Last_Name]) as [Insured Name], --- (Check Comment 3)
DatefromParts([OCLSCN]*100+[OCLSYY],[OCLSMM],[OCLSDD]) as [Occurrence Date], --- (CMOCUR db)
rtrim(ltrim(OCDACC)) as [Cause of Loss], --- (CMOCUR db)
DatefromParts([OCRPCN]*100+[OCRPYY],[OCRPMM],[OCRPDD]) as [Claim Reported Date], --- (CMOCUR db)
iif(LSSETLD is null,'', LSSETLD) as [Settled Indicator], --- (Check Comment 2)
--iif(SUM([Incurred Loss NET OF S&S]) - SUM([Paid Loss NET OF S&S]) = 0, 'Closed', 'Open') as [Status in AS-400]
iif(OCCLCN=0,'',datefromparts(OCCLCN*100+OCCLYY,OCCLMM,OCCLDD)) as [Closed Date], --- (CMOCUR db)
iif(LSCLCN=0 OR LSCLCN IS NULL,'',DatefromParts(LSCLCN*100+LSCLYY,LSCLMM,LSCLDD)) as [All Closed Date] ----(Comment 2)
--[Last Reserve Change Date]
FROM AS400.FRTDTA250.CMOCUR
LEFT JOIN Lookups.dbo.[Bad CAT Codes] ON [Claim Nbr] = OCCMNR ---- This LEFT JOIN provides the CAT CODE for this report (Comment 1)
LEFT JOIN AS400.FRTDTA250.CMLSCP ON LSCMNR = OCCMNR ---- This is used to pull any COMMENTS and SETTLEMENT made on a claim (Comment 2)
LEFT JOIN Lookups.dbo.Insured_Name_By_PolicyNum ON Prefix = OCPRFX and Polnum = OCPLNR --- This is to add the INSURED NAME (comment 3)
So, the issue i am having is that i have this other sub-queries that are meant to provide information for the [Status in AS-400] and [Last Reserve Change Date]. How do i connect this queries to the SQL?
Below are the 2 queries that i am trying to add to the select query:
-- Query for [Status in AS-400]
SELECT
---s1.[Claim Number],
iif(SUM(s1.[Incurred Loss NET OF S&S]) - SUM(s1.[Paid Loss NET OF S&S]) = 0, 'Closed', 'Open') as [Open / Closed]
---SUM(s1.[Incurred Loss NET OF S&S]) - SUM(s1.[Paid Loss NET OF S&S]) as [Loss C/R]
FROM
(
SELECT
OCCMNR as [Claim Number],
SUM(iif(DATASETTYPE IN ('Incurred LOSS'), CTTRAM, iif(DATASETTYPE IN ('SALVAGE','SUBROGATION','OTHER RECOVERIES'), -CTTRAM, 0))) AS [Incurred Loss NET OF S&S],
SUM(iif(DATASETTYPE IN ('Paid LOSS'), CTTRAM, iif(DATASETTYPE IN ('SALVAGE','SUBROGATION','OTHER RECOVERIES'), -CTTRAM, 0))) AS [Paid Loss NET OF S&S]
FROM AS400.FRTDTA250.[CMOCUR] AS A
INNER JOIN AS400.FRTDTA250.[CMTRAN]AS B ON A.OCCMNR = B.CTCMNR
LEFT JOIN Lookups.dbo.TransactionCodes AS C ON B.CTGRPC = C.TransactionCode
WHERE DATEFROMPARTS(CTTRCN*100+CTTRYY, CTTRMM, CTTRDD) <= #asofdate
and CTTRSB not in (4,12)
and CTTSCD = 'P'
GROUP BY OCCMNR
) as s1
GROUP BY s1.[Claim Number]
ORDER BY s1.[Claim Number]
--Query for [Last Reserve Change Date]
Select [Claim Number],
left(convert(CHAR, Max([Loss Transaction Date]), 120),10) as [Last Reserve Change Date]
From
(
Select [OCCMNR] as [Claim Number],
DATEFROMPARTS(CTTRCN*100+CTTRYY, CTTRMM, CTTRDD) as [Loss Transaction Date],
iif(DATASETTYPE IN ('Incurred LOSS'), CTTRAM, 0) as [Incurred Loss]
From AS400.FRTDTA250.[CMTRAN] as b1
LEFT JOIN AS400.FRTDTA250.[CMOCUR] as a1
ON a1.OCCMNR = b1.CTCMNR
LEFT JOIN Lookups.dbo.TransactionCodes as c1
ON b1.CTGRPC = c1.TransactionCode
Where (iif(DATASETTYPE IN ('Incurred LOSS'), CTTRAM, 0) <> 0)
and DATEFROMPARTS(CTTRCN*100+CTTRYY, CTTRMM, CTTRDD) <= #asofdate
and CTTRSB not in (4,12)
AND CTTSCD = 'P'
) s2
group by [Claim Number]
) as G
on G.[Claim Number] = a.[OCCMNR]
And i use a MS-SQL Server

Format for joining Sub-queries are as follows:
SELECT *
FROM TABLEA A
INNER JOIN TABLED D on A.ID = D.ID
LEFT JOIN
( SELECT B.ID,COLUMN_A
FROM TABLEB B
INNER JOIN TABLEC C ON B.ID = C.ID
) X ON A.ID = X.ID

Related

Explain how this sql syntax works from Access in SQL Server

I have an access database that I am converting to SQL Server and there is a report that has the follow:
SELECT tblInventoryUnit.[ORG-IU],
tblInventoryUnit.[Parent ORG Name],
tblVehicle.[Asset Tag Number],
tblVehicle.[Vehicle Unit Type],
tblVehicle.[Historical Unit Number],
tblVehicle.[License Plate Number],
tblVehicle.[Model Year],
tblVehicle.Make,
tblVehicle.Model,
tblVehicle.[Acquisition Date],
tblVehicle.[Vehicle Cost],
tblVehicle.[Insurance Account],
tblVehicle.[Insurance Sub-Account],
tblVehicle.[Project Code],
tblFSOTeams.[Fund Accountant Team],
tblVehicle.[Vehicle Status]
FROM tblSPSTeams
RIGHT JOIN(tblFSOTeams
INNER JOIN(tblInventoryUnit
INNER JOIN tblVehicle
ON tblInventoryUnit.[ORG-IU] = tblVehicle.[ORG-IU])
ON tblFSOTeams.[Org Number] = tblInventoryUnit.[Parent ORG])
ON tblSPSTeams.[Account Number] = tblVehicle.[Insurance Account]
WHERE (
((tblVehicle.[Vehicle Unit Type]) <> 'TA')
AND ((tblVehicle.[Acquisition Date]) < '7/15/2020')
AND
(
(tblVehicle.[Vehicle Status]) = 'Pending - Motor Pool'
OR (tblVehicle.[Vehicle Status]) = 'Active - In Use'
OR (tblVehicle.[Vehicle Status]) = 'Active - Unlocated'
OR (tblVehicle.[Vehicle Status]) = 'Active - Surplused'
)
AND ((tblSPSTeams.[SPS Team Number]) IS NULL)
)
OR
(
((tblVehicle.[Vehicle Unit Type]) <> 'TA')
AND ((tblVehicle.[Acquisition Date]) < '7/15/2020')
AND ((tblVehicle.[Vehicle Status]) = 'Inactive')
AND ((tblSPSTeams.[SPS Team Number]) IS NULL)
AND ((tblVehicle.[Disposal Date]) > '7/1/2020')
);
I have figured out from looking at the diagram that this equals:
SELECT tblInventoryUnit.[ORG-IU],
tblInventoryUnit.[Parent ORG Name],
tblVehicle.[Asset Tag Number],
tblVehicle.[Vehicle Unit Type],
tblVehicle.[Historical Unit Number],
tblVehicle.[License Plate Number],
tblVehicle.[Model Year],
tblVehicle.Make,
tblVehicle.Model,
tblVehicle.[Acquisition Date],
tblVehicle.[Vehicle Cost],
tblVehicle.[Insurance Account],
tblVehicle.[Insurance Sub-Account],
tblVehicle.[Project Code],
tblFSOTeams.[Fund Accountant Team],
tblVehicle.[Vehicle Status]
FROM dbo.tblVehicle
LEFT JOIN dbo.tblSPSTeams
ON dbo.tblVehicle.[Insurance Account] = dbo.tblSPSTeams.[Account Number]
INNER JOIN dbo.tblInventoryUnit
ON tblInventoryUnit.[ORG-IU] = tblVehicle.[ORG-IU]
INNER JOIN dbo.tblFSOTeams
ON tblFSOTeams.[Org Number] = dbo.tblInventoryUnit.[Parent ORG]
WHERE (
((tblVehicle.[Vehicle Unit Type]) <> 'TA')
AND ((tblVehicle.[Acquisition Date]) < '7/15/2020')
AND
(
(tblVehicle.[Vehicle Status]) = 'Pending - Motor Pool'
OR (tblVehicle.[Vehicle Status]) = 'Active - In Use'
OR (tblVehicle.[Vehicle Status]) = 'Active - Unlocated'
OR (tblVehicle.[Vehicle Status]) = 'Active - Surplused'
)
AND ((tblSPSTeams.[SPS Team Number]) IS NULL)
)
OR
(
((tblVehicle.[Vehicle Unit Type]) <> 'TA')
AND ((tblVehicle.[Acquisition Date]) < '7/15/2020')
AND ((tblVehicle.[Vehicle Status]) = 'Inactive')
AND ((tblSPSTeams.[SPS Team Number]) IS NULL)
AND ((tblVehicle.[Disposal Date]) > '7/1/2020')
);
Can someone explain how the first query works? I don't get the syntax. In particular, this part:
FROM tblSPSTeams
RIGHT JOIN(tblFSOTeams
INNER JOIN(tblInventoryUnit
INNER JOIN tblVehicle
ON tblInventoryUnit.[ORG-IU] = tblVehicle.[ORG-IU])
ON tblFSOTeams.[Org Number] = tblInventoryUnit.[Parent ORG])
ON tblSPSTeams.[Account Number] = tblVehicle.[Insurance Account]
It looks like two subqueries but there is no select statement in the inner tables. I tried to add a select statement like a "normal" subquery but it balked at the idea. How exactly does this work? Is there a special syntax that I am not getting?

using sql subtotals

I have the following select statement:
SELECT
c.compname AS [Company]
,x.Ressnavn AS [Client]
,a.jobid AS [Job Number]
,a.JobNavn AS [Job Name]
,t.TName [Task Name]
,cu.DayDate AS [Booking Date]
,cu.HrsBooked AS [Scheduled Hours]
,tr.Sale AS [Sales Value]
,(cu.HrsBooked) * (tr.Sale) AS [Total]
FROM job a
INNER JOIN jobplan jp on jp.JobId=a.jobid
INNER JOIN JobDimensions AS z ON z.jobid = a.jobid
INNER JOIN Ress AS x ON x.RessId = z.custid
INNER JOIN JobPrice AS y ON y.JobId = a.Jobid
INNER JOIN task t on t.PlanId = jp.PlanId
INNER JOIN JobPriceactivity AS w ON w.priceId = y.priceId
INNER JOIN taskres tr ON tr.TaskId = t.TaskId
INNER JOIN emp e ON e.EmpId = tr.ResId
INNER JOIN comp c ON e.compid = c.compid
INNER JOIN CapUsed AS cu ON cu.RefId = tr.TaskResId AND cu.RefType=1
INNER JOIN arpaccount AS ar ON e.empname = ar.arpaccname
AND CAST (cu.DayDate AS DATE) BETWEEN #startdate AND #enddate
WHERE c.compid = '107' AND e.EMPID >='2' AND cu.HrsBooked > '0'
GROUP BY
x.Ressnavn
,a.jobid
,a.JobNavn
,t.TName
,cu.DayDate
,cu.HrsBooked
,y.priceid
,tr.Sale
,c.compname
That gives me the following output but I would like to add in a subtotal of the column 'Total' at each change in client.
An example of what I would like to try and get to is highlighted in green on the output screen grab.
Can anyone advise on the best way to do this?
Try using GROUP BY ROLLUP:
SELECT
x.Ressnavn AS [Client],
c.compname AS [Company],
a.jobid AS [Job Number],
a.JobNavn AS [Job Name],
t.TName [Task Name],
cu.DayDate AS [Booking Date],
cu.HrsBooked AS [Scheduled Hours],
tr.Sale AS [Sales Value],
(cu.HrsBooked) * (tr.Sale) AS [Total]
FROM (...)
GROUP BY
x.Ressnavn,
ROLLUP (
c.compname,
a.jobid,
a.JobNavn,
t.TName,
cu.DayDate,
cu.HrsBooked,
y.priceid,
tr.Sale )

MS Access Help to run a query

I have two tables as follows.
I want to get all members who are active and payment period = fortnightly and corresponding savings record for each member for a specific year and month. Note that some of the members may not have a savings record for given year and month.
I have a query written, but it does not return the members who does not have a savings record in savings table.
SELECT Member.memberID As [ID],Member.firstName AS [First Name],
Member.lastName AS [Last Name], Member.paymentPeriod AS [Payment Period],
Savings.savingId AS [Savings Id], Savings.enteredAmount AS [Amount]
FROM Member
LEFT JOIN Savings ON Member.memberID = Savings.memberId
WHERE Member.isActive = 'Active' AND Member.paymentPeriod = 'Fortnightly'
AND Year(Savings.enteredDate)=2019 AND Month(Savings.enteredDate) = 1;
Move the SAVINGS conditions from WHERE to ON to get true LEFT JOIN result:
SELECT Member.memberID As [ID],Member.firstName AS [First Name],
Member.lastName AS [Last Name], Member.paymentPeriod AS [Payment Period],
Savings.savingId AS [Savings Id], Savings.enteredAmount AS [Amount]
FROM Member
LEFT JOIN Savings ON Member.memberID = Savings.memberId
AND Year(Savings.enteredDate)=2019 AND Month(Savings.enteredDate) = 1
WHERE Member.isActive = 'Active' AND Member.paymentPeriod = 'Fortnightly';
(With those conditions in the WHERE clause, you'll get regular INNER JOIN result.)
Edit: Attempt to avoid "Join expression not supported error":
SELECT Member.memberID As [ID],Member.firstName AS [First Name],
Member.lastName AS [Last Name], Member.paymentPeriod AS [Payment Period],
Savings.savingId AS [Savings Id], Savings.enteredAmount AS [Amount]
FROM Member
LEFT JOIN Savings ON Member.memberID = Savings.memberId
WHERE Member.isActive = 'Active' AND Member.paymentPeriod = 'Fortnightly'
AND (Year(Savings.enteredDate)=2019 or Year(Savings.enteredDate) IS NULL)
AND (Month(Savings.enteredDate) = 1 or Month(Savings.enteredDate) IS NULL);

Joining two views

I'm after some help please. I only use ms access and beginning to use SQL I have two views part1 and part2 I can't join them and get any results( I have the results from MS access ( see below results part ) . I need the same results to show in SQL )
Thank you..
View (part1)
select Mvpr.Prefix, Mvpr.SubKey1 AS [Parkers Part Number], Mvpr.SubKey2 AS [Supplier Code], Mvpr.A12 AS [Supplier Part Number], vwProduct.Psupp as part1
FROM vwProduct INNER JOIN Mvpr ON vwProduct.KeyCode = Mvpr.SubKey1
WHERE Mvpr.Prefix ='c'
View (part2)
SELECT dbo.RHeads.Document, RLines.Part, RHeads.Supp, RHeads.[DateTime], RLines.Unit, RLines.CQty, RLines.ClCost, RHeads.POrder, RHeads.Corder, RHeads.Branch as part2
FROM RHeads INNER JOIN RLines ON RHeads.Document = RLines.Document
WHERE RHeads.[DateTime] >= DATEADD(MONTH, -3, GETDATE())
Result
SELECT part1.Document, part1.Part [Parkers Part], part2.[Supplier Part Number], part1.Supp [Supplier Code], part1.Unit [Unit Price], part1.CQty [Qty Recieved], dbo.vwProduct.SI18 Surcharge, part1.POrder, part1.Corder, part1.Branch, part1.DateTime
FROM dbo.vwProduct INNER JOIN part2 INNER JOIN part1 ON part2.[Supplier Code] = part1.Supp AND part2.[Parkers Part Number] = part1.Part ON dbo.vwProduct.KeyCode = part1.Part
GROUP BY part1.Document, part1.Part, part2.[Supplier Part Number], part1.Supp, part1.Unit, part1.CQty, dbo.vwProduct.SI18, part1.POrder, part1.Corder, part1.Branch, part1.DateTime
Based on your SQL in Result section, your View (part2) should be your part1 since columns such as Document, Part, etc. are coming from that and vice versa.
SELECT part1.Document,
part1.Part [Parkers Part],
part2.[Supplier Part Number],
part1.Supp [Supplier Code],
part1.Unit [Unit Price],
part1.CQty [Qty Recieved],
dbo.vwProduct.SI18 Surcharge,
part1.POrder,
part1.Corder,
part1.Branch,
part1.DateTime
FROM dbo.vwProduct
INNER JOIN part1
ON dbo.vwProduct.KeyCode = part1.Part
INNER JOIN part2
ON part2.[Supplier Code] = part1.Supp
AND part2.[Parkers Part Number] = part1.Part
GROUP BY part1.Document,
part1.Part,
part2.[Supplier Part Number],
part1.Supp,
part1.Unit,
part1.CQty,
dbo.vwProduct.SI18,
part1.POrder,
part1.Corder,
part1.Branch,
part1.DateTime

SQL select statement that checks two columns and returns the value from a third [duplicate]

This question already has answers here:
SQL Server Error:"SQL Server Subquery returned more than 1 value"
(2 answers)
Closed 7 years ago.
I am writing a query that accesses multiple tables in the same database. For one of the columns in the select statement, I need to return
Table1.Column4
where Table1.Column = Table3.Column1 AND
Table1.Column2 = Table4.Column1
I have it written as:
SELECT AccNum.FieldValue
FROM PersonFieldValuesVW
INNER JOIN PersonFieldValuesVW AccNum
ON AccNum.PersonId = InPerson.PersonId
INNER JOIN InPerson
ON InPerson.IncidentId = Incident.Id
WHERE AccNum.FieldDescr like '%Account Number%') as [Account Number],
This is returning the error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Here is the full query, any assistance would be appreciated.
SELECT DISTINCT
CaseNum as [Case Number],
ALCategoryVW.Category as [Category],
ALCategoryVW.SubCategory as [Sub Category],
InAssign.AssignToName as [Assigned To],
ReportedDate as [Open Date],
EndDate as [Closed Date], --This a placeholder for a closed date
[Status],
SiteLoc1.Descr as [Loss Location],
LocDetails as [Loss Cost Center],
SiteLoc1.Region as [Region],
SiteLoc1.SubRegion as [Sub Region],
-- SiteLoc2.Descr as [Location Description], **Need this though returning all for the location?
CASE WHEN SAR.FieldId = '604NU' and SAR.FieldValue <> 'False' THEN 'YES' ELSE 'NO' END as [SAR Required],
Summary as [Incident Summary],
Disposition as [Case Disposition],
(
SELECT AccNum.FieldValue
FROM PersonFieldValuesVW
INNER JOIN PersonFieldValuesVW AccNum ON AccNum.PersonId = InPerson.PersonId
INNER JOIN InPerson ON InPerson.IncidentId = Incident.Id
WHERE AccNum.FieldDescr like '%Account Number%'
) as [Account Number],
FORMAT(AuditItemDetail.ItemValue, '#,###') as [Potential Loss],
FORMAT(AuditItemDetail.ItemValue - AuditItemDetail.PreventedExposureAmount, '#,###') as [Actual Loss]
FROM Incident
INNER JOIN ALCategoryVW ON ALCategoryVW.IncidentId = Incident.Id
INNER JOIN InAssign ON InAssign.IncidentId = Incident.Id
INNER JOIN SiteLoc1 ON SiteLoc1.Id = Incident.LocId
INNER JOIN SiteLoc2 ON SiteLoc2.SiteLoc1Id = SiteLoc1.Id
INNER JOIN IncidentFieldValuesVW SAR ON SAR.IncidentId = Incident.Id
INNER JOIN InItem ON InItem.IncidentId = Incident.Id
INNER JOIN AuditItemDetail ON AuditItemDetail.ItemId = InItem.ItemId
INNER JOIN InPerson ON InPerson.IncidentId = Incident.Id
INNER JOIN PersonFieldValuesVW AccNum ON AccNum.PersonId = InPerson.PersonId
This should resolve your error, but I'm not sure it is logically correct. If you have two records being returned in the sub-select, which one is the "right" one.
SELECT DISTINCT
CaseNum as [Case Number],
ALCategoryVW.Category as [Category],
ALCategoryVW.SubCategory as [Sub Category],
InAssign.AssignToName as [Assigned To],
ReportedDate as [Open Date],
EndDate as [Closed Date], --This a placeholder for a closed date
[Status],
SiteLoc1.Descr as [Loss Location],
LocDetails as [Loss Cost Center],
SiteLoc1.Region as [Region],
SiteLoc1.SubRegion as [Sub Region],
-- SiteLoc2.Descr as [Location Description], **Need this though returning all for the location?
CASE WHEN SAR.FieldId = '604NU' and SAR.FieldValue <> 'False' THEN 'YES' ELSE 'NO' END as [SAR Required],
Summary as [Incident Summary],
Disposition as [Case Disposition],
AccNum.FieldValue,
FORMAT(AuditItemDetail.ItemValue, '#,###') as [Potential Loss],
FORMAT(AuditItemDetail.ItemValue - AuditItemDetail.PreventedExposureAmount, '#,###') as [Actual Loss]
FROM Incident
INNER JOIN ALCategoryVW ON ALCategoryVW.IncidentId = Incident.Id
INNER JOIN InAssign ON InAssign.IncidentId = Incident.Id
INNER JOIN SiteLoc1 ON SiteLoc1.Id = Incident.LocId
INNER JOIN SiteLoc2 ON SiteLoc2.SiteLoc1Id = SiteLoc1.Id
INNER JOIN IncidentFieldValuesVW SAR ON SAR.IncidentId = Incident.Id
INNER JOIN InItem ON InItem.IncidentId = Incident.Id
INNER JOIN AuditItemDetail ON AuditItemDetail.ItemId = InItem.ItemId
INNER JOIN InPerson ON InPerson.IncidentId = Incident.Id
LEFT JOIN PersonFieldValuesVW AccNum ON AccNum.PersonId = InPerson.PersonId AND AccNum.FieldDescr like '%Account Number%'
***Updated based on comment.