CREATE FUNCTION [dbo].[GetBalanceAddressType] (@AReferenceNumber INT, @AGuestNumber INT, @AAddressType INT)
RETURNS MONEY
AS
/*
  Created by Kent Johansen, December 2018
  Notes:
*/
BEGIN
  DECLARE @Total MONEY

  SELECT @Total = SUM(Transactions.PriceOverwrite * (CASE WHEN (Accounts.AccountType IN (4, 9)) THEN -1 ELSE 1 END) * (CASE WHEN (Transactions.Debit = 0) THEN -1 ELSE 1 END)) 
  FROM Transactions WITH (NOLOCK) 
  INNER JOIN Accounts WITH (NOLOCK) ON Accounts.AccountNumber = Transactions.AccountNumber
  INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = Transactions.FolioNumber
  INNER JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = Folios.ReservationAddressNumber
    AND (@AAddressType <= 0 OR ReservationAddress.AddressType = @AAddressType)
  WHERE Folios.ReferenceNumber = @AReferenceNumber
  AND Folios.GuestNumber = @AGuestNumber 
  AND ShowOnBillFlag = 1 
  AND MovedDeleted = 0

  IF @Total < 0.01 AND @Total > -0.01 
    SET @Total = 0

  RETURN @Total * -1
END