How to Create an SQL Query for the Balance Aging Report in SAP Business One - featured image

Publications

How to Create an SQL Query for Balance Aging Report in SAP Business One

Hector Pincheira

Hector Pincheira

CIO | CTO
Digital Strategy & Technology Innovation

items

The Inconvenient Truth Behind Your Accounts Receivable

There is one question that every CFO and CEO should be able to answer in less than 30 seconds: How much money do my clients owe me and for how long? If your answer depends on opening SAP Business One, navigating three menus, waiting for the standard report to load, and then exporting to Excel to «format it»... you have a management problem, not a technology problem.

The Aging Report is one of the most critical tools for the financial health of any company. However, the standard SAP Business One report has real limitations: it does not always show the granularity you need, it does not allow for quick customizations, and above all, it is not designed to easily integrate into dashboards or automated processes. This is where the SAP Business One aging report customized using SQL makes a difference.

In this tutorial, we are going to build from scratch a SQL query that will give you a complete aging report, with configurable buckets (30, 60, 90, more than 90 days), grouped by customer and assigned sales employee, ready to use in the SAP B1 Query Manager. And the best part: I will give you the versions for both MS SQL Server sort of like SAP HANA.

Why Do You Need a Customized Aging Report?

The impact of failing to monitor the age of your accounts receivable is direct and measurable: deteriorated cash flow, tied-up working capital, and business decisions made in the dark. I’ve seen industrial companies with more than 40% of their receivables past due by more than 90 days, simply because no one had real-time visibility. As I mentioned in my article on SAP, Information and Power, information that does not turn into action is just noise.

If you do not implement an agile tracking mechanism, what happens is predictable: the sales team keeps selling to delinquent customers, the finance department discovers the problems too late, and management makes decisions based on intuition rather than data. A customized aging report allows you to move from reactivity to anticipation.

Prerequisites

  • SAP Business One 9.3 or higher (compatible with versions 10.x)
  • Access to Query Manager (Tools menu → Queries → Query Manager)
  • Read permissions about the tables OCRD, JDT1, OINV, OSLP
  • Database: MS SQL Server 2016+ or SAP HANA
  • Finance and Active Business Partner Management Module

Step-by-Step Tutorial: Building the Aging Report Query

Step 1: Understand the Tables Involved

Before writing a single line of SQL, you need to understand the data structure. In SAP Business One, accounts receivable information is distributed primarily across these tables:

  • JDT1 (Journal Entry Lines): Contains all journal entry lines. Here lives the detail of each transaction with its due date (Due Date), debit amount (Debit), credit amount (Credit) and the remaining balance (Balance Due Debt, Balance Due Credit).
  • OCRD (Business Partners): Business partner master data with code, name, customer group, and assigned sales representative.
  • OSLP (Sales Employees): Table of salespeople to identify who manages each account.
  • OCRG (BP Groups): Business partner groups for segmentation.
💡 Pro tip: Many consultants make the mistake of building the aging report from OINV (A/R invoices). The problem is that this ignores credit memos, partial payments, and accounting adjustments. The JDT1 table reflects the REAL balance because it includes all transactions that affect the customer's account.

Step 2: The Base Query for MS SQL Server

Open the Query Manager in SAP B1 (Tools → Queries → Query Manager) and create a new query. This is the complete query that we are going to break down line by line:

-- Customer Aging Report
-- SAP Business One - MS SQL Server
-- Author: Héctor Pincheira
SELECT
    T0."CardCode"                              AS 'Client Code',
    T0."CardName"                              AS 'Customer Name',
    T2."SlpName"                               AS 'Seller',
    T0."CreditLine"                            AS 'Credit Limit',
    T0."Balance"                               AS 'Total Balance',
    -- Bucket: Not due (future)
    SUM(CASE
        WHEN DATEDIFF(DAY, T1."DueDate", GETDATE()) <= 0
        THEN (T1."Balance Due Debit" - T1."BalDueCred")
        ELSE 0
    END)                                        AS 'Not Defeated',
    -- Bucket: 1-30 days past due
    SUM(CASE
        WHEN DATEDIFF(DAY, T1."DueDate", GETDATE()) BETWEEN 1 AND 30
        THEN (T1."Balance Due Debit" - T1."BalDueCred")
        ELSE 0
    END)                                        AS '1-30 Days',
    -- Bucket: 31-60 days past due
    SUM(CASE
        WHEN DATEDIFF(DAY, T1."DueDate", GETDATE()) BETWEEN 31 AND 60
        THEN (T1."Balance Due Debit" - T1."BalDueCred")
        ELSE 0
    END)                                        AS '31-60 Days',
    -- Bucket: 61-90 days past due
    SUM(CASE
        WHEN DATEDIFF(DAY, T1."DueDate", GETDATE()) BETWEEN 61 AND 90
        THEN (T1."Balance Due Debit" - T1."BalDueCred")
        ELSE 0
    END)                                        AS '61-90 Days',
    -- Bucket: Over 90 days past due
    SUM(CASE
        WHEN DATEDIFF(DAY, T1."DueDate", GETDATE()) > 90
        THEN (T1."Balance Due Debit" - T1."BalDueCred")
        ELSE 0
    END)                                        AS 'More Than 90 Days'
FROM OCR D T0
INNER JOIN JDT1 T1 On T0."CardCode" = T1."ShortName"
Left Join OSLP T2 On T0."SlpCode" = T2."SlpCode"
WHERE T0."CardType" = 'C'
  AND T0."Balance" > 0
  AND (T1."Balance Due Debit" - T1."BalDueCred") != 0
group by
    T0."CardCode",
    T0."CardName",
    T2."SlpName",
    T0."CreditLine",
    T0."Balance"
ORDER BY
    'More Than 90 Days' DESC, T0."Balance" DESC

Step 3: Line-by-Line Breakdown

Let's understand each section of this query, because copying and pasting without understanding is exactly what separates an operator from a strategist:

The base columns (CardCode, CardName, SlpName, CreditLine, Balance): We extract the customer's ID, their assigned salesperson, the credit limit configured in SAP, and the current total balance. The credit limit is key because it allows you to immediately calculate the utilization percentage.

The aging buckets: Each block SUM(CASE...) calculates a range of overdue days. The function DATEDIFF(DAY, T1."DueDate", GETDATE()) Subtract the due date of each item from the current date. If the result is negative or zero, the item is not yet due. If it is positive, it indicates the days past due.

The JOIN with JDT1: We connect the business partner master data (OCRD) with the journal entry lines (JDT1) through the field Short Name, which in JDT1 contains the business partner code. This is the link that gives us access to each individual transaction.

The WHERE clause: CardType = 'C' filter only customers (no vendors or leads). Balance > 0 Exclude customers with no balance. And (BalDueDeb - BalDueCred) != 0 Delete already settled items.

⚠️ Warning: The field Balance in OCRD shows the balance in local currency. If you work with multiple currencies, consider using Foreign Balance for foreign currency balances, or BalanceSys for system currency.

SAP Business One receivables aging report - SQL code and data analysis

Step 4: SAP HANA Version

If your SAP Business One runs on HANA, the logic is identical, but the date syntax changes. HANA uses DAYS_BETWEEN instead of DATEDIFF and Current date instead of GETDATE():

-- Aging Report - SAP HANA
SELECT
    T0."CardCode"                              AS "Customer Code",
    T0."CardName"                              AS "Customer Name",
    T2."SlpName"                               AS "Seller",
    T0."CreditLine"                            AS "Credit Limit",
    T0."Balance"                               AS "Total Balance",
    SUM(CASE
        WHEN DAYS_BETWEEN(T1."DueDate", Current date) <= 0
        THEN (T1."Balance Due Debit" - T1."BalDueCred")
        ELSE 0
    END)                                        AS "Not Defeated",
    SUM(CASE
        WHEN DAYS_BETWEEN(T1."DueDate", Current date) BETWEEN 1 AND 30
        THEN (T1."Balance Due Debit" - T1."BalDueCred")
        ELSE 0
    END)                                        AS "1-30 Days",
    SUM(CASE
        WHEN DAYS_BETWEEN(T1."DueDate", Current date) BETWEEN 31 AND 60
        THEN (T1."Balance Due Debit" - T1."BalDueCred")
        ELSE 0
    END)                                        AS "31-60 Days",
    SUM(CASE
        WHEN DAYS_BETWEEN(T1."DueDate", Current date) BETWEEN 61 AND 90
        THEN (T1."Balance Due Debit" - T1."BalDueCred")
        ELSE 0
    END)                                        AS "61-90 Days",
    SUM(CASE
        WHEN DAYS_BETWEEN(T1."DueDate", Current date) > 90
        THEN (T1."Balance Due Debit" - T1."BalDueCred")
        ELSE 0
    END)                                        AS "More Than 90 Days"
FROM OCR D T0
INNER JOIN JDT1 T1 On T0."CardCode" = T1."ShortName"
Left Join OSLP T2 On T0."SlpCode" = T2."SlpCode"
WHERE T0."CardType" = 'C'
  AND T0."Balance" > 0
  AND (T1."Balance Due Debit" - T1."BalDueCred") != 0
group by
    T0."CardCode",
    T0."CardName",
    T2."SlpName",
    T0."CreditLine",
    T0."Balance"
ORDER BY
    "More Than 90 Days" DESC, T0."Balance" DESC
💡 Pro tip: In HANA, DAYS_BETWEEN(start_date, end_date) returns a positive number when the end date is after the start date. This is the opposite of how some developers expect it to work, so verify your logic before running in production.

Step 5: Add the Report to the Query Manager

To make this query permanently available in SAP Business One, follow these steps:

  1. Open SAP B1 and go to Tools → Queries → Query Manager.
  2. In the Query Manager window, create a new category called «Custom Financial Reports» (if it does not exist).
  3. Click on «New» and paste the corresponding query for your database (MS SQL or HANA).
  4. Assign a descriptive name: «Aging – Aging Report by Customer».
  5. Save and run. You will see the results ordered by customers with the highest overdue debt past 90 days.

The result will show you a table with each customer, their salesperson, the credit limit, the total balance, and the aging distribution. This is exactly what you need for an effective collection meeting or to feed a dashboard in BI tools like Qlik Sense.

Variations and Advanced Cases of the Aging Report

Variation 1: Filter by Specific Vendor

If you want each salesperson to see only their customers, add a parameter to the WHERE clause. In MS SQL Server:

AND T2."SlpName" = '[%0]'
-- SAP B1 will display a field to enter the salesperson's name

Variation 2: Include Credit Utilization Percentage

Add this calculated column after «Total Balance» to see what percentage of the assigned credit each customer is using:

CASE
    WHEN T0."CreditLine" > 0
    THEN CAST(ROUND((T0."Balance" / T0."CreditLine") * 100, 1) AS VARCHAR) + '%'
    ELSE 'Without Limit'
END AS ''% Credit Usage''

Variation 3: Aging for Accounts Payable (Suppliers)

Just change the filter CardType = 'C' by CardType = 'S' (Suppliers) and you will have the same report for your suppliers. This is essential for planning your cash flow from both perspectives, something I discussed in the context of the importance of clean data in SAP.

SAP Business One receivables aging report - laptop with financial analysis

Common Mistakes and Best Practices

After implementing this query at multiple companies, these are the mistakes I see repeated over and over:

  1. Using OINV instead of JDT1: As I mentioned earlier, the invoice table does not reflect partial payments or applied credit notes. Always use JDT1 for the real balance.
  2. Ignoring the BalDueCred field: If you only add up Balance Due Debt, you will inflate the balances because you are not subtracting the credited entries (payments, credit notes).
  3. Not filtering closed entries: Without the filter (BalDueDeb - BalDueCred) != 0, you will include thousands of zero-balance records that slow the query down without adding information.
  4. Confusing DueDate with RefDate: Due Date is the entry's actual due date. Reference Date is the document date. For correct aging, always use Due Date.
  5. Not considering multi-currency: In companies that operate with multiple currencies, check whether you need the foreign currency fields (BalFcDeb, BalFcCred) or the system currency ones.
💡 Pro tip: Schedule this query as a recurring report sent every Monday to the collections team and every Friday to the finance manager. In SAP B1 you can do it from Tools → My Alerts, creating a query-based alert. For a more complete automation strategy, see how agentic AI is transforming processes in SAP.

Official SAP Resources

Conclusion: From Data to the Collections Decision

With this query you have much more than a report: you have a decision tool. You know exactly how much each customer owes you, for how long, who the responsible salesperson is and whether the customer has already exceeded their credit limit. That is actionable intelligence, not a PDF nobody reads.

The natural next step is taking this report to an automated dashboard — whether with BI tools like Qlik Sense or even with Crystal Reports embedded in SAP B1. What matters is that you stop relying on Excel as the middleman and put the data where it belongs: in front of whoever makes the decisions.

Do you already have an automated aging process in your company? What tweaks would you make to this query to fit your reality? Share your experience in the comments — every company has its particularities and together we build better solutions.

Most Read

QlikSense Hierarchy: parent-child chart of accounts expanded by levels
QlikSense Hierarchy: the Chart of Accounts That Doesn't Add Up
QlikSense Sum TOTAL: share of each family over the total
QlikSense Sum TOTAL: the Percentage That Changes When You Filter
SAP Business One Inventory Revaluation - featured image of the tutorial
SAP Business One Inventory Revaluation: Fix Wrongly Loaded Costs
Empty chamber with wooden benches: the counterweight that required being present to be used
The Veto You Had to Say in Person: Your Decisions With No Counterweight
SAP Business One customizations - featured image of the pre-upgrade audit tutorial
SAP Business One Customizations: Pre-Upgrade Audit
SAP Business One Customer Concentration - featured image of the tutorial
SAP Business One Customer Concentration: Measure Your Risk with SQL

RELATED ARTICLES