How do I Exclude Rows When All Correlated Subqueries Return Null - sql-server-2012

I have a list of parts from a supplier and I want to see what we've bought and sold since Jan 1. I created subqueries for the sales and purchasing info.
There are four possibilities in the results:
Sales Quantity = Purchase Quantity
Sales Quantity > Purchase Quantity (including NULL Purchase Quantity)
Sales Quantity < Purchase Quantity (including NULL Sales Quantity)
Both Sales and Purchase Quantities are NULL
How do I exclude rows when both Sales and Purchase Quantity is NULL while retaining those rows which may have a NULL Sales Quantity or Purchase Quantity? An image is attached to show examples of these scenarios.
I reviewed this thread, but it does not seem to apply because my columns do not have to be equal.
SELECT DISTINCT
p21_view_supplier.supplier_id AS [Supp ID],
p21_view_supplier.supplier_name AS Supplier,
p21_view_inv_mast.item_id AS [Item ID],
p21_view_inv_mast.item_desc AS [Item Desc],
p21_view_inv_loc.location_id AS [Location ID],
invoice_data.[Total Shipped by Sales Loc],
purchase_data.[PO Qty Ordered]
FROM
p21_view_supplier
INNER JOIN p21_view_inventory_supplier ON p21_view_supplier.supplier_id = p21_view_inventory_supplier.supplier_id
INNER JOIN p21_view_inv_mast ON p21_view_inventory_supplier.inv_mast_uid = p21_view_inv_mast.inv_mast_uid
INNER JOIN p21_view_inv_loc ON p21_view_inv_mast.inv_mast_uid = p21_view_inv_loc.inv_mast_uid
--Invoices
LEFT JOIN (
SELECT
p21_view_invoice_hdr.sales_location_id,
p21_view_invoice_line.item_id,
p21_view_invoice_line.supplier_id,
p21_view_invoice_line.inv_mast_uid,
SUM(p21_view_invoice_line.qty_shipped) AS [Total Shipped by Sales Loc]
FROM
p21_view_invoice_hdr
INNER JOIN p21_view_invoice_line ON p21_view_invoice_hdr.invoice_no = p21_view_invoice_line.invoice_no
WHERE
(p21_view_invoice_hdr.invoice_date >= CONVERT(DATETIME, '2016-01-01 00:00:00', 102))
GROUP BY
p21_view_invoice_hdr.sales_location_id,
p21_view_invoice_line.item_id,
p21_view_invoice_line.supplier_id,
p21_view_invoice_line.inv_mast_uid
) invoice_data ON p21_view_supplier.supplier_id = invoice_data.supplier_id
AND p21_view_inv_mast.inv_mast_uid = invoice_data.inv_mast_uid
AND p21_view_inv_loc.location_id = invoice_data.sales_location_id
--Purchasing
LEFT JOIN (
SELECT
p21_view_po_hdr.supplier_id,
p21_view_po_hdr.location_id AS [PO Loc ID],
SUM(p21_view_po_line.qty_ordered) AS [PO Qty Ordered],
p21_view_po_line.item_id AS [Item ID],
p21_view_po_line.inv_mast_uid
FROM
p21_view_po_hdr
INNER JOIN p21_view_po_line ON p21_view_po_hdr.po_no = p21_view_po_line.po_no
WHERE
(p21_view_po_hdr.date_created >= CONVERT(DATETIME, '2016-01-01 00:00:00', 102))
AND (p21_view_po_hdr.delete_flag IS NULL OR
p21_view_po_hdr.delete_flag = 'N')
AND (p21_view_po_line.delete_flag IS NULL OR
p21_view_po_line.delete_flag = 'N')
AND (p21_view_po_line.cancel_flag IS NULL OR
p21_view_po_line.cancel_flag = 'N')
AND (p21_view_po_hdr.cancel_flag IS NULL OR
p21_view_po_hdr.cancel_flag = 'N')
GROUP BY
p21_view_po_hdr.supplier_id,
p21_view_po_hdr.location_id,
p21_view_po_line.item_id,
p21_view_po_line.inv_mast_uid
) purchase_data ON p21_view_supplier.supplier_id = purchase_data.supplier_id
AND p21_view_inv_mast.inv_mast_uid = purchase_data.inv_mast_uid
AND p21_view_inv_loc.location_id = purchase_data.[PO Loc ID]
WHERE
(p21_view_supplier.supplier_id = 8761)
AND (p21_view_inv_mast.delete_flag = 'N')
ORDER BY
p21_view_inv_mast.item_id,
p21_view_inv_loc.location_id

Assuming there is at least one not nullable column in both of the derived tables, you can simply add a condition to the outer query where clause, that will evaluate to true only if at least one of the non nullable columns in the derived tables is not null.
In this case, I'm assuming that the non-nullable column is the same for both derived tables and it's supplier_id, So I add to the where clause the following condition:
AND NOT (purchase_data.supplier_id is null and invoice_data.supplier_id is null)
The full query:
SELECT DISTINCT
p21_view_supplier.supplier_id AS [Supp ID],
p21_view_supplier.supplier_name AS Supplier,
p21_view_inv_mast.item_id AS [Item ID],
p21_view_inv_mast.item_desc AS [Item Desc],
p21_view_inv_loc.location_id AS [Location ID],
invoice_data.[Total Shipped by Sales Loc],
purchase_data.[PO Qty Ordered]
FROM
p21_view_supplier
INNER JOIN p21_view_inventory_supplier ON p21_view_supplier.supplier_id = p21_view_inventory_supplier.supplier_id
INNER JOIN p21_view_inv_mast ON p21_view_inventory_supplier.inv_mast_uid = p21_view_inv_mast.inv_mast_uid
INNER JOIN p21_view_inv_loc ON p21_view_inv_mast.inv_mast_uid = p21_view_inv_loc.inv_mast_uid
--Invoices
LEFT JOIN (
SELECT
p21_view_invoice_hdr.sales_location_id,
p21_view_invoice_line.item_id,
p21_view_invoice_line.supplier_id,
p21_view_invoice_line.inv_mast_uid,
SUM(p21_view_invoice_line.qty_shipped) AS [Total Shipped by Sales Loc]
FROM
p21_view_invoice_hdr
INNER JOIN p21_view_invoice_line ON p21_view_invoice_hdr.invoice_no = p21_view_invoice_line.invoice_no
WHERE
(p21_view_invoice_hdr.invoice_date >= CONVERT(DATETIME, '2016-01-01 00:00:00', 102))
GROUP BY
p21_view_invoice_hdr.sales_location_id,
p21_view_invoice_line.item_id,
p21_view_invoice_line.supplier_id,
p21_view_invoice_line.inv_mast_uid
) invoice_data ON p21_view_supplier.supplier_id = invoice_data.supplier_id
AND p21_view_inv_mast.inv_mast_uid = invoice_data.inv_mast_uid
AND p21_view_inv_loc.location_id = invoice_data.sales_location_id
--Purchasing
LEFT JOIN (
SELECT
p21_view_po_hdr.supplier_id,
p21_view_po_hdr.location_id AS [PO Loc ID],
SUM(p21_view_po_line.qty_ordered) AS [PO Qty Ordered],
p21_view_po_line.item_id AS [Item ID],
p21_view_po_line.inv_mast_uid
FROM
p21_view_po_hdr
INNER JOIN p21_view_po_line ON p21_view_po_hdr.po_no = p21_view_po_line.po_no
WHERE
(p21_view_po_hdr.date_created >= CONVERT(DATETIME, '2016-01-01 00:00:00', 102))
AND (p21_view_po_hdr.delete_flag IS NULL OR
p21_view_po_hdr.delete_flag = 'N')
AND (p21_view_po_line.delete_flag IS NULL OR
p21_view_po_line.delete_flag = 'N')
AND (p21_view_po_line.cancel_flag IS NULL OR
p21_view_po_line.cancel_flag = 'N')
AND (p21_view_po_hdr.cancel_flag IS NULL OR
p21_view_po_hdr.cancel_flag = 'N')
GROUP BY
p21_view_po_hdr.supplier_id,
p21_view_po_hdr.location_id,
p21_view_po_line.item_id,
p21_view_po_line.inv_mast_uid
) purchase_data ON p21_view_supplier.supplier_id = purchase_data.supplier_id
AND p21_view_inv_mast.inv_mast_uid = purchase_data.inv_mast_uid
AND p21_view_inv_loc.location_id = purchase_data.[PO Loc ID]
WHERE
(p21_view_supplier.supplier_id = 8761)
AND (p21_view_inv_mast.delete_flag = 'N')
AND NOT (purchase_data.supplier_id is null and invoice_data.supplier_id is null)
ORDER BY
p21_view_inv_mast.item_id,
p21_view_inv_loc.location_id

Related

How to add a column to existing query to show data with different date range values?

I want to show [Net Revenue] and [Prior Net Revenue] in the same query. The start and end date ranges are supplied by user. When the query is run, desired output should be:
CustID, CustName, InvoiceDate, NetRevenue, PriorNetRevenue
Note: PriorNetRevenue is for the previous year. So if user enters InvoiceStartDate = '2018-06-30' and InvoiceEndDate = '2019-06-30' then PriorNetRevenue should be from '2017-06-30' and '2018-06-30' for the same customer.
Thanks for your help in advance.
DECLARE #InvcStartDate datetime = '2018-06-30'
DECLARE #InvcEndDate datetime = '2019-06-30'
SELECT * from
(SELECT
p.CustID as [Cust ID],
p.CustName as [Cust Name],
p.InvcDate as [Invoice Date]
SUM(NetRevenue) as [Net Revenue]
FROM ProfitReport p (nolock)
LEFT JOIN Cust_view v (nolock) ON p.CustID = v.CustId
WHERE p.InvcDate BETWEEN #InvcStartDate AND #InvcEndDate
and p.CustType IN ('New','Old')
GROUP BY
p.CustID,
p.CustName,
p.InvcDate) as c1
INNER JOIN
(SELECT
p.CustID as [Cust ID],
p.CustName as [Cust Name],
p.InvcDate as [Invoice Date]
SUM(NetRevenue) as [PRIOR Net Revenue]
FROM ProfitReport p (nolock)
LEFT JOIN Cust_view v (nolock) ON p.CustID = v.CustId
WHERE p.InvcDate BETWEEN #InvcStartDate AND #InvcEndDate
and p.CustType IN ('New','Old')
GROUP BY
p.CustID,
p.CustName,
p.InvcDate) as c2
on c1.[Cust ID] = c2.[Cust ID]
The problem is invoice date is different for different years. I also tried using UNION but it just results in data duplication.
One way of achieving the goal is to use a CTE which calculates the previous years revenue per customer then join this on to your main query.
declare #InvcStartDate date = '2018-06-30', #InvcEndDate date = '2019-06-30';
declare #ProfitReport table (
CustId int,
CustName nvarchar(15),
InvcDate date,
NetRevenue float,
CustType nvarchar(3)
);
declare #Cust_View table (
CustId int
);
insert #Cust_View
values
(1),
(2),
(3),
(4);
insert #ProfitReport (CustId, CustName, InvcDate, NetRevenue, CustType)
values
(1, 'Bob', '2017-07-01', 500.75, 'Old'),
(2, 'Linda', '2018-02-05', 320.13, 'Old'),
(1, 'Steve', '2018-07-06', 612.04, 'New'),
(2, 'Jane', '2019-05-18', 130.00, 'Old');
with previousyear as ( SELECT
p.CustID as [Cust ID],
p.CustName as [Cust Name],
p.InvcDate as [Invoice Date],
SUM(NetRevenue) as [Net Revenue]
FROM #ProfitReport p
LEFT JOIN #Cust_view v ON p.CustID = v.CustId
WHERE p.InvcDate BETWEEN dateadd(year, -1, #InvcStartDate) AND dateadd(year, -1, #InvcEndDate)
and p.CustType IN ('New','Old')
GROUP BY
p.CustID,
p.CustName,
p.InvcDate)
SELECT
p.CustID as [Cust ID],
p.CustName as [Cust Name],
p.InvcDate as [Invoice Date],
SUM(p.NetRevenue) as [Net Revenue],
p2.[Net Revenue] as [Prior Net Revenue]
FROM #ProfitReport p
LEFT JOIN #Cust_view v ON p.CustID = v.CustId
left join previousyear p2 on p.CustId=p2.[Cust ID]
WHERE p.InvcDate BETWEEN #InvcStartDate AND #InvcEndDate
and p.CustType IN ('New','Old')
GROUP BY
p.CustID,
p.CustName,
p.InvcDate,
p2.[Net Revenue];

Oracle SQL -- Count (*) where value is used multiple times, need to include NULL

I am trying to include results where some Problem Types are shared by multiple ID's and may contain a NULL on one but not on the other. Example: EPISY_EMS has a Problem Type of Client Relations and so does EPISY_EPISYS. The EMS product has a count of 10 and the EPISYS product has a count of 0 but doesn't display at all in the results, how can I get that to show as 0 or Null?
Select c.Product_id as [Product ID], b.DESCR as [Product Descr],
a.RC_SS_IND as [Self-Service Available], a.RC_SHORT_DESCR as [Problem Type],
COUNT(*) as [Count]
From PS_RC_CASE c
JOIN PS_RC_PROBTYPE_TBL a on c.PROBLEM_TYPE = a.PROBLEM_TYPE
AND c.Product_ID = a.Product_ID
JOIN PS_PROD_ITEM b on c.PRODUCT_ID = b.PRODUCT_ID
WHERE b.EFF_STATUS = 'A'
AND c.Creation_Date > '2017-01-01 00:00:00.000'
AND a.RC_SS_IND = 'Y'
AND a.RC_SHORT_DESCR in ('Client Relations', 'Implementation', 'General Ledger')
AND C.Product_ID in ('EPISY_CHOICE', 'EPISY_CKIMRT', 'EPISY_COLDOCTK', 'EPISY_EMS')
GROUP BY a.RC_SHORT_DESCR, a.PRODUCT_ID,
b.DESCR, a.RC_SS_IND,
b.product_id, c.PRODUCT_ID
Order By b.DESCR asc

How can I optimised this query since it is causing locks

Its causing locks and I need help optimising it...
Select o.Vehicle as [No Unit], o.Customer, o.CustomerDisplayName as Name, o.Product as Material, P.ProductName as Product,
o.Depot as Works, a.Distance, o.CustTravelTime as [Assumed TravelTime], o.RequiredDateTime as [Required DateTime],o.TimeWindowOrder
as [To Window Provided],ToWindowDateTime as [Window DateTime],o.OrderRef as [Ref No], o.OrderEntryDateTime as [Orderred DateTime],
o.EnteredBy, o.Instructions, o.Warnings, o.Planning, o.AllocationState as Status,o.LoadDocket as Docket, o.LoadingDateTime
as [Commenced Loading], o.IntransitDateTime as [Completed Loading], o.ArrivedDateTime as [Arrived Customer], o.ArrivedDateTime
as [Commenced Unloading], o.UnloadedDateTime as [Completed Unloading], '?' as [DMS], o.CustomerOrder as CustPO,
o.Renegotiated, o.TurnAround, o.StockOut, o.LateDelivery,o.LateOrder,o.StandingOrder,o.NightShift,o.modifier
as [Actual Modifier], t2.Net, t2.Trantype,o.PlannedDateTime, o.VehAssignedDateTime as [Published Date],
t2.DriverName, o.CancelledDateTime from Orders o left outer join Product P on p.Product = o.Product
left outer join AuthPlantCust A on a.Customer = o.Customer and a.Plant = o.Plant --left
join trans T on O.orderref = t.orderref
outer apply ( SELECT Top 1 Docket, Trantype, DriverName, Net FROM Trans t where o.Orderref = t.Orderref AND TranType <> 'SRT'
ORDER BY DespatchdateTime Desc ) T2 where o.RequiredDateTime >= (#DespatchFrom)
and o.RequiredDateTime < (#DespatchTo) and o.Company = 'C' order by o.RequiredDateTime, o.OrderRef
Or advise best practices.

SQL: How do I show all Items in Inventory and Sum sales of items sold in a time period?

I am trying to find all items on hand from #Supplier_ID and summarize any sales since #Begin_Date. What is returned are all items on hand that have never been sold and those sold since #Begin_Date. Items on hand that were sold before #Begin_Date are excluded from the results. How do I fix that?
I am using SQL Server 2012 and SSRS v3.
SELECT DISTINCT
inventory_supplier.supplier_id AS [Supp ID],
address.name AS Supplier,
inv_loc.location_id AS [Inventory Loc ID],
inv_mast.item_id AS [Item ID],
inv_mast.item_desc AS [Item Desc],
inv_loc.qty_on_hand AS QOH,
inv_loc.moving_average_cost AS MAC,
invoice_line.qty_shipped,
invoice_hdr.customer_id AS [Customer ID],
invoice_hdr.bill2_name AS Customer,
oe_line.source_loc_id AS [Sales Source Loc]
FROM
inventory_supplier
INNER JOIN
inv_mast ON inventory_supplier.inv_mast_uid = inv_mast.inv_mast_uid
INNER JOIN
address ON inventory_supplier.supplier_id = address.id
FULL OUTER JOIN
invoice_line ON inv_mast.inv_mast_uid = invoice_line.inv_mast_uid
FULL OUTER JOIN
inv_loc ON inv_mast.inv_mast_uid = inv_loc.inv_mast_uid
FULL OUTER JOIN
invoice_hdr ON invoice_line.invoice_no = invoice_hdr.invoice_no
FULL OUTER JOIN
oe_line ON invoice_hdr.order_no = oe_line.order_no
AND invoice_line.inv_mast_uid = oe_line.inv_mast_uid
WHERE
(inventory_supplier.supplier_id = #Supplier_ID)
AND (invoice_hdr.invoice_date >= #Begin_Date
OR invoice_hdr.invoice_date IS NULL)
AND (inv_loc.qty_on_hand > 0)
ORDER BY
[Item ID], [Inventory Loc ID], [Customer ID], [Sales Source Loc]
You could move your invoice_hdr.invoice_date >= #Begin_Date to your join statement
FULL OUTER JOIN
invoice_hdr ON invoice_line.invoice_no = invoice_hdr.invoice_no
AND invoice_hdr.invoice_date >= #Begin_Date
Don't see a lot of FULL OUTER JOINs. Sure you don't want LEFT JOIN here?
You might want to separate out the Invoice information from the Inventory information into a subquery, and LEFT JOIN to the Invoice information.
SELECT DISTINCT
inventory_supplier.supplier_id AS [Supp ID],
address.name AS Supplier,
inv_loc.location_id AS [Inventory Loc ID],
inv_mast.item_id AS [Item ID],
inv_mast.item_desc AS [Item Desc],
inv_loc.qty_on_hand AS QOH,
inv_loc.moving_average_cost AS MAC,
invoices.qty_shipped,
invoices.customer_id AS [Customer ID],
invoices.bill2_name AS Customer,
invoices.source_loc_id AS [Sales Source Loc]
FROM
inventory_supplier
INNER JOIN
inv_mast ON inventory_supplier.inv_mast_uid = inv_mast.inv_mast_uid
INNER JOIN
address ON inventory_supplier.supplier_id = address.id
INNER JOIN
inv_loc ON inv_mast.inv_mast_uid = inv_loc.inv_mast_uid
LEFT OUTER JOIN
(SELECT
invoice_line.inv_mast_uid,
invoice_line.qty_shipped,
invoice_hdr.customer_id,
invoice_hdr.bill2_name,
oe_line.source_loc_id
FROM
invoice_line
INNER JOIN
invoice_hdr ON invoice_line.invoice_no = invoice_hdr.invoice_no
INNER JOIN
oe_line ON invoice_hdr.order_no = oe_line.order_no
AND invoice_line.inv_mast_uid = oe_line.inv_mast_uid
WHERE
invoice_hdr.invoice_date >= #Begin_Date
) invoices ON invoices.inv_mast_uid = inv_mast.inv_mast_uid
WHERE
inventory_supplier.supplier_id = #Supplier_ID
AND inv_loc.qty_on_hand > 0
ORDER BY
[Item ID], [Inventory Loc ID], [Customer ID], [Sales Source Loc]
Try changing
WHERE
(inventory_supplier.supplier_id = #Supplier_ID)
AND (invoice_hdr.invoice_date >= #Begin_Date
OR invoice_hdr.invoice_date IS NULL)
AND (inv_loc.qty_on_hand > 0)
to
WHERE
(inventory_supplier.supplier_id = #Supplier_ID)
AND (invoice_hdr.invoice_date >= #Begin_Date)
AND (inv_loc.qty_on_hand > 0)
The problem is because you are including dates, invoice_hdr.invoice_date that are NULL in the WHERE clause. Simply remove it:
WHERE
(inventory_supplier.supplier_id = #Supplier_ID)
AND (invoice_hdr.invoice_date >= #Begin_Date)
AND (inv_loc.qty_on_hand > 0)

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.