I have a SQL query that works as expected, and I turned it into a view. When I then query the view, I get a handful of records that are wrong, and I cannot figure out why. I have researched the issue and recreated the view, to no avail.
This is the original query:
SELECT
a.Name AS 'Asset Name',
invs.Asset__c AS 'Asset Id',
acc.Account_Management_Team__c AS 'Account Management Team',
SUM(
CASE
WHEN invs.Markup_Percentage__c = 0 OR invs.Markup_Percentage__c IS NULL THEN COALESCE(invs.Labor_Total__c, 0) + COALESCE(invs.Misc_Total__c, 0) + COALESCE(invs.Parts_Total__c, 0)
ELSE
ROUND(((COALESCE(invs.Labor_Total__c, 0) * (invs.Markup_Percentage__c + 100) / 100) +
(COALESCE(invs.Misc_Total__c, 0) * (invs.Markup_Percentage__c + 100) / 100) +
(COALESCE(invs.Parts_Total__c, 0) * (invs.Markup_Percentage__c + 100) / 100)),2)
END
) AS 'Grand Total Final Before Tax'
FROM dbo.Location_History__c lh
LEFT JOIN dbo.Account acc ON lh.Assigned_Account__c = acc.Id
LEFT JOIN dbo.Invoice_Segment__c invs ON lh.Id = invs.Asset_Location_History__c
LEFT JOIN dbo.Invoice__c i ON invs.Invoice__c = i.Id
LEFT JOIN dbo.Asset a ON lh.Asset__c = a.Id
WHERE
invs.[RecordTypeId] <> '0127V000000DzbDQAS' -- Exclude rentals
AND i.[Status__c] = 'Approved' -- Approved invoices only
AND invs.Repair_Category__c <> 'Contract Maintenance' -- Exclude contract maintenance
AND invs.[Repair_Category__c] IS NOT NULL
GROUP BY a.Name, invs.Asset__c, acc.Account_Management_Team__c
And this is a (correct) sample result:
+-----------------------+--------------------+-------------------------+------------------------------+
| Asset Name | Asset Id | Account Management Team | Grand Total Final Before Tax |
+-----------------------+--------------------+-------------------------+------------------------------+
| XXX_2C6000_AT83F42883 | 02i3t00000UPLnzAAH | XXX | 66369.70000000 |
+-----------------------+--------------------+-------------------------+------------------------------+
This is the view query:
SELECT *
FROM [dbo].[pbi-ftf-asset-expense]
And this is a sample result (the first row is wrong):
+-----------------------+--------------------+-------------------------+------------------------------+
| Asset Name | Asset Id | Account Management Team | Grand Total Final Before Tax |
+-----------------------+--------------------+-------------------------+------------------------------+
| XXX_2C6000_AT83F42839 | 02i3t00000UPLnzAAH | XXX | 252.07000000 |
| XXX_2C6000_AT83F42883 | 02i3t00000UPLnzAAH | XXX | 66369.70000000 |
+-----------------------+--------------------+-------------------------+------------------------------+
What could be going on here, and how can I fix it? I have a total of 20 records out of almost 17K that are wrong, and I’m at a loss as to why this is happening.