I have a query that I am trying to get to display rows no matter what. The query returns correct info for what I need if there is some data returned, but in cases where all rows are null, I am getting nothing, obviously, and instead of nothing, I need a row returning all 0’s if not.
I have tried using isnull() and coalesce() to account for this, but I’m not doing it right, apparently. Below is my base query that I need to adjust for this purpose.
SELECT
Vendor
,SUM(TotalAssigned) as 'Total Production Assigned Not Completed'
,SUM(AssignedFees) as 'Work in process Fees'
,SUM(TotalSubmitted) as 'Total Production Submitted'
,SUM(SubmittedFees) as 'Submitted Production Fees'
FROM(
SELECT
distinct
v.ContactFirstName+' '+v.ContactLastName AS Vendor
,oi.orderid, oi.orderitemid
,CASE WHEN oi.QueueID > 0 and oi.lastmilestoneid < 70 THEN 1 ELSE 0 END AS TotalAssigned
,CASE WHEN oi.QueueID > 0 and oi.lastmilestoneid < 70 THEN dbo.GetAdjustedVendorFee(oi.OrderID, oi.OrderItemID) END AS AssignedFees
,CASE WHEN oim.MilestoneID = 70 THEN 1 ELSE 0 END AS TotalSubmitted
,CASE WHEN oim.MilestoneID = 70 THEN dbo.GetAdjustedVendorFee(oi.OrderID, oi.OrderItemID) END AS SubmittedFees
FROM
OrderItems oi
LEFT JOIN OrderItemMilestones oim ON oim.OrderID = oi.OrderID and oim.OrderItemID = oi.OrderItemID
LEFT JOIN Vendors v ON v.VendorID = oi.VendorID
WHERE
oim.MilestoneDate BETWEEN dbo.TruncateDate(dateadd(dd, -1, Current_Timestamp)) and dbo.TruncateDate(Current_Timestamp)
and oi.VendorID in (105144)
and oi.productid not in (105)
)x
GROUP BY Vendor
One way is to wrap your expression in a CTE and then
UNION ALLit withUNION ALL SELECT NULL, 0,0,0,0 WHERE NOT EXISTS(SELECT * FROM CTE)e.g.
Here’s a demo with a less complicated statement