How to Analyze Profitability by Customer in SAP Business One with SQL Queries - featured image

Publications

How to Analyze Profitability by Customer in SAP Business One with SQL Queries

Hector Pincheira

Hector Pincheira

CIO | CTO
Digital Strategy & Technology Innovation

items

Do you really know which of your customers generate profit and which are costing you money? Consequently, analyzing the SAP Business One customer profitability it becomes a strategic necessity that goes far beyond reviewing sales volume. However, many companies continue to measure commercial success solely by revenue, without considering the actual margins behind each business relationship.

In this tutorial, I will also show you step-by-step how to build advanced SQL queries in the SAP Business One Query Manager to obtain a complete profitability analysis by customer. This way, you will be able to identify your most and least profitable customers, make informed decisions regarding pricing strategies, and therefore, optimize your sales mix.

SAP Business One customer profitability - financial analysis dashboard
Profitability analysis transforms invoicing data into actionable business intelligence

Why You Need to Measure Profitability by Customer in Your Business

The Pareto Principle applies strongly to sales management: approximately 20% of your customers generate 80% of your profit. However, what many managers don’t realize is that there is a percentage of customers who, despite generating significant revenue, actually destroy value. For example, customers with aggressive discounts, frequent returns, or low-margin products may be consuming resources without contributing real profitability.

Therefore, the standard SAP Business One report shows gross profit at the document level, but it does not offer a consolidated view that allows comparing customers with each other. As a result, you need to create custom queries that cross-reference information from invoices, credit memos, and costs to get the full picture. In this way, you transform transactional data into strategic intelligence.

Prerequisites for This Tutorial

Before you begin, also make sure you have the following:

  • Access to Query Manager of SAP Business One (Tools menu → Queries → Query Manager)
  • Read permissions about the OINV, INV1, ORIN, RIN1, and OCRD tables
  • Basic SQL knowledge (SELECT, JOIN, GROUP BY, CASE)
  • Data from at least 3 months for billing so that the analysis is representative
  • Professional License or higher (the Query Manager is not available in the Starter license)

Key Tables for SAP Business One Customer Profitability Analysis

First of all, it is essential to understand which tables are involved in this analysis. Below, I detail each one and its specific role:

  • OCRDBusiness Partner Master Data. Contains the code, name, group, and assigned sales employee for each customer.
  • OINV / INV1Customer invoices (header and lines). Sales amounts, costs, and gross profit per line live here.
  • ORIN / RIN1Credit notes (header and lines). However, many forget to include them, which distorts the analysis.
  • OSLPSales Master. Allows segmenting profitability by sales force.

The most relevant fields within INV1 and RIN1 are, for example: Line Total (net line amount), Gross Profit (gross profit calculated by SAP), Stock price (item cost) and Quantity. Consequently, by combining these fields, you get an accurate X-ray of each customer.

Step-by-Step Tutorial: Customer Profitability Query

Query 1: Customer Profitability Ranking with Gross Margin

This first query provides a complete ranking of customers sorted by gross profit. It also includes the sales margin percentage, making it easy to quickly identify which customers are high-volume with low margin. Therefore, it is the ideal starting point for any profitability analysis.

SQL Server

-- Customer profitability ranking - SQL Server
SELECT TOP 50
    T0.CardCode                              AS [Customer Code],
    T0.CardName                              AS [Customer Name],
    T2.SlpName                               AS [Seller],
    Count(DISTINCT T0.DocEntry              AS [Invoice Numbers],
    SUM(T1.LineTotal)                        AS Net Sales,
    SUM(T1.GrssProfit)                      AS Gross Profit,
    CASE WHEN SUM(T1.LineTotal) > 0
         THEN ROUND(SUM(T1.GrssProfit) / SUM(T1.LineTotal) * 100, 2)
         ELSE 0
    END                                       AS [Margin 1Q3Q],
    SUM(T1.LineTotal) - SUM(T1.GrssProfit)  AS Total Cost
FROM OINV T0 WITH (NOLOCK)
INNER JOIN INV1 T1 WITH (NOLOCK) On T0.DocEntry = T1.DocEntry
Left Join OSLP T2 On T0.SlpCode = T2.SlpCode
WHERE T0.CANCELED = 'N'
  AND T0.DocDate >= DATEADD(MONTH, -6, GETDATE())
group by T0.CardCode, T0.CardName, T2.SlpName
ORDER BY Gross Profit DESC

SAP HANA

-- Customer profitability ranking - SAP HANA
SELECT
    T0."CardCode"                              AS "Client Code,
    T0."CardName"                              AS "Customer Name",
    T2."SlpName"                               AS "Salesperson,
    Count(DISTINCT T0."DocEntry"              AS "Invoice No.,
    SUM(T1."LineTotal")                        AS "Net Sales,
    SUM(T1."GrssProfit")                      AS "Gross Profit,
    CASE WHEN SUM(T1."LineTotal") > 0
         THEN ROUND(SUM(T1."GrssProfit") / SUM(T1."LineTotal") * 100, 2)
         ELSE 0
    END                                         AS ""1Q-3Q Margin",
    SUM(T1."LineTotal") - SUM(T1."GrssProfit") AS "Total Cost"
FROM "OINV T0
INNER JOIN "INV1" T1 On T0."DocEntry" = T1."DocEntry"
Left Join "OSLP" T2 On T0."SlpCode" = T2."SlpCode"
WHERE T0."CANCELED" = 'N'
  AND T0."DocDate" >= ADD_MONTHS(Current date, -6)
group by T0."CardCode", T0."CardName", T2."SlpName"
ORDER BY "Gross Profit" DESC
LIMIT 50
SAP Business One customer profitability - data analysis on screen
Custom queries transform SAP transactional data into business decisions

Query 2: Net Profitability Including Credit Notes

The first query is useful, but it has a major limitation: it does not consider credit notes. Consequently, a customer with many returns may appear profitable when they actually are not. Therefore, this second version integrates invoices and credit notes to obtain the real net profitability.

SQL Server

-- Net profitability per customer (invoices - credit memos) - SQL Server
SELECT
    C.CardCode                               AS [Code],
    C.CardName                               AS [Client],
    S.SlpName                                AS [Seller],
    ISNULL(F.VentaNeta, 0)                   AS [Sales],
    ISNULL(NC.MontoNC, 0)                    AS Credit Notes,
    ISNULL(Net Sales, 0) - ISNULL(NC.MontoNC, 0) AS [Real Sale],
    ISNULL(F.Profit, 0) - ISNULL(NC.GananciaNC, 0) AS [Net Income],
    CASE WHEN (ISNULL(Net Sales, 0) - ISNULL(NC.MontoNC, 0)) > 0
         THEN ROUND(
              (ISNULL(F.Profit, 0) - ISNULL(NC.GananciaNC, 0)) /
              (ISNULL(Net Sales, 0) - ISNULL(NC.MontoNC, 0)) * 100, 2)
         ELSE 0
    END                                       AS [Net Margin 1Q-3Q]
FROM OCRD C
Left Join OSLP S On C.SlpCode = S.SlpCode
Left Join (
    SELECT T0.CardCode,
           SUM(T1.LineTotal) AS NetSales,
           SUM(T1.GrssProfit) AS Profit
    FROM OINV T0 WITH (NOLOCK)
    INNER JOIN INV1 T1 WITH (NOLOCK) On T0.DocEntry = T1.DocEntry
    WHERE T0.CANCELED = 'N'
      AND T0.DocDate >= DATEADD(MONTH, -6, GETDATE())
    group by T0.CardCode
) F On C.CardCode = F.CardCode
Left Join (
    SELECT T0.CardCode,
           SUM(T1.LineTotal) AS MontoNC,
           SUM(T1.GrssProfit) AS Net Profit
    FROM ORIN T0 WITH (NOLOCK)
    INNER JOIN RIN1 T1 WITH (NOLOCK) On T0.DocEntry = T1.DocEntry
    WHERE T0.CANCELED = 'N'
      AND T0.DocDate >= DATEADD(MONTH, -6, GETDATE())
    group by T0.CardCode
) NC On C.CardCode = NC.CardCode
WHERE C.CardType = 'C'
  AND (ISNULL(NetSales, 0) > 0 OR ISNULL(NC.MontoNC, 0) > 0)
ORDER BY Net Income DESC

SAP HANA

-- Net profitability per customer (invoices - credit memos) - SAP HANA
SELECT
    C."CardCode"                               AS "Code",
    C."CardName"                               AS "Client",
    S."SlpName"                                AS "Salesperson,
    IFNULL(F."VentaNeta", 0)                   AS "Sales,
    IFNULL(NC."MontoNC", 0)                    AS "Credit Memos,
    IFNULL(F."VentaNeta", 0) - IFNULL(NC."MontoNC", 0) AS "Venta Real,
    IFNULL(F."Profit", 0) - IFNULL(NC."GananciaNC", 0) AS "Net Income,
    CASE WHEN (IFNULL(F."VentaNeta", 0) - IFNULL(NC."MontoNC", 0)) > 0
         THEN ROUND(
              (IFNULL(F."Profit", 0) - IFNULL(NC."NonOperatingProfit", 0)) /
              (IFNULL(F."VentaNeta", 0) - IFNULL(NC."MontoNC", 0)) * 100, 2)
         ELSE 0
    END                                         AS ""Net Margin 1Q-3Q""
FROM "OCRD" C
Left Join "OSLP" S On C."SlpCode" = S."SlpCode"
Left Join (
    SELECT T0."CardCode",
           SUM(T1."LineTotal") AS "VentaNeta",
           SUM(T1."GrssProfit") AS "Ganancia"
    FROM "OINV T0
    INNER JOIN "INV1" T1 On T0."DocEntry" = T1."DocEntry"
    WHERE T0."CANCELED" = 'N'
      AND T0."DocDate" >= ADD_MONTHS(Current date, -6)
    group by T0."CardCode"
) F On C."CardCode" = F."CardCode"
Left Join (
    SELECT T0."CardCode",
           SUM(T1."LineTotal") AS "MontoNC",
           SUM(T1."GrssProfit") AS "GananciaNC"
    FROM "ORIN" T0
    INNER JOIN "RIN1" T1 On T0."DocEntry" = T1."DocEntry"
    WHERE T0."CANCELED" = 'N'
      AND T0."DocDate" >= ADD_MONTHS(Current date, -6)
    group by T0."CardCode"
) NC On C."CardCode" = NC."CardCode"
WHERE C."CardType" = 'C'
  AND (IFNULL(F."VentaNeta", 0) > 0 OR IFNULL(NC."MontoNC", 0) > 0)
ORDER BY "Ganancia Neta" DESC

Variations and Advanced Use Cases

ABC Customer Segmentation by Profitability

Once you have gross profit per customer, you can also classify them automatically into A, B and C segments. That way the sales team can prioritize effort on the highest-value customers. Here is how to add that classification to the query.

SQL Server

-- ABC classification by profitability - SQL Server
SELECT
    CardCode, CardName, GananciaBruta, MargenPct,
    CASE
        WHEN PctAcumulado <= 80 THEN 'A - Strategic'
        WHEN PctAcumulado <= 95 THEN 'B - Important'
        ELSE 'C - Review'
    END AS [Segmento]
FROM (
    SELECT
        T0.CardCode, T0.CardName,
        SUM(T1.GrssProfit) AS GananciaBruta,
        ROUND(SUM(T1.GrssProfit) / NULLIF(SUM(T1.LineTotal), 0) * 100, 2) AS MargenPct,
        SUM(SUM(T1.GrssProfit)) OVER (ORDER BY SUM(T1.GrssProfit) DESC) /
        SUM(SUM(T1.GrssProfit)) OVER () * 100 AS PctAcumulado
    FROM OINV T0 WITH (NOLOCK)
    INNER JOIN INV1 T1 WITH (NOLOCK) On T0.DocEntry = T1.DocEntry
    WHERE T0.CANCELED = 'N'
      AND T0.DocDate >= DATEADD(YEAR, -1, GETDATE())
    group by T0.CardCode, T0.CardName
    Having SUM(T1.GrssProfit) > 0
) Sub
ORDER BY GananciaBruta DESC

SAP HANA

-- ABC classification by profitability - SAP HANA
SELECT
    "CardCode", "CardName", "GananciaBruta", "MargenPct",
    CASE
        WHEN "PctAcumulado" <= 80 THEN 'A - Strategic'
        WHEN "PctAcumulado" <= 95 THEN 'B - Important'
        ELSE 'C - Review'
    END AS "Segmento"
FROM (
    SELECT
        T0."CardCode", T0."CardName",
        SUM(T1."GrssProfit") AS "GananciaBruta",
        ROUND(SUM(T1."GrssProfit") / NULLIF(SUM(T1."LineTotal"), 0) * 100, 2) AS "MargenPct",
        SUM(SUM(T1."GrssProfit")) OVER (ORDER BY SUM(T1."GrssProfit") DESC) /
        SUM(SUM(T1."GrssProfit")) OVER () * 100 AS "PctAcumulado"
    FROM "OINV T0
    INNER JOIN "INV1" T1 On T0."DocEntry" = T1."DocEntry"
    WHERE T0."CANCELED" = 'N'
      AND T0."DocDate" >= ADD_YEARS(Current date, -1)
    group by T0."CardCode", T0."CardName"
    Having SUM(T1."GrssProfit") > 0
) Sub
ORDER BY "GananciaBruta" DESC
SAP Business One customer profitability - financial analysis chart
ABC segmentation lets you put commercial resources where they generate the most return

Best Practices and Common Mistakes

When you implement these queries, though, it is important to avoid the common mistakes that can distort the results. First, always filter out cancelled documents with CANCELED = 'N'; otherwise you will be counting duplicated amounts. Also remember that SAP Business One stores credit notes with positive amounts in the ORIN/RIN1 tables, so you have to subtract them explicitly.

Another common mistake is ignoring the inventory valuation method. If your company uses Moving Average, for example, the field Gross Profit reflects the average cost at the time of the invoice. If you use FIFO or Standard Price, however, the values can differ. So make sure the cost recorded in INV1 matches your accounting expectation.

Here are some other key recommendations:

  • Run the queries during low-load hours: these queries cross high-volume tables, so they can hit server performance at peak times.
  • Parameterize the dates: instead of hardcoding periods, use dynamic parameters ([%0] and [%1] in Query Manager) so the user picks the range.
  • Validate against the standard reports: compare your query totals against SAP's Sales Analysis report to make sure they are consistent.
  • Include posted documents only: filter with DocStatus = 'C' if you want to exclude drafts or open documents.

Official SAP Resources

To go deeper into the tables and fields used, you can also check these official resources:

  • SAP Business One SDK Help: detailed documentation of the OINV, INV1, ORIN and RIN1 tables with a description of every field.
  • SAP Community: an active forum where consultants share queries and answer questions about custom reports.
  • SAP Help Portal: implementation guides for the sales module and configuration of costing methods.
  • SAP Learning Hub: courses on Query Manager and Crystal Reports for SAP Business One.

Conclusion: From Data to Strategic Decisions

To measure the SAP Business One customer profitability is not an isolated technical exercise. It is a management tool that changes the relationship between the sales area and the finance function. So when you implement these queries and turn them into recurring reports, you create an early-warning system that catches the customers destroying value before the damage is irreversible.

The ABC classification also lets you allocate commercial resources intelligently: more attention for the A customers, improvement strategies for the B customers, and hard but necessary decisions for the C customers. Your team stops chasing volume and starts building sustainable profitability.

The real power of this analysis, though, is in the action you take with the results. You can renegotiate commercial terms, adjust discounts or redesign your price structure. Every query you run becomes a concrete step toward a leaner, more competitive company.

Want to keep mastering SAP Business One from the trenches? Join the Círculo Estratégico and get exclusive tutorials that will transform how you run your business.

Most Read

Ballena jorobada bajo el agua con su aleta pectoral extendida: la esperanza en la tecnología y la biomimética
La ballena que volvió: la esperanza en la tecnología y la que no cabe en un tablero
SAP data in ChatGPT: an open door at the far end of a dark room
The Tab Next Door: The SAP Data in ChatGPT That Nobody Authorized
SAP Business One Purchase Price Variance - featured image of the tutorial
SAP Business One Purchase Price Variance: Detect the Inflation in Your Buying Costs
QlikSense format changeovers: actual minutes against the standard
QlikSense Format Changeovers: the Minutes Nobody Bills
QlikSense buttons and actions: executive dashboard with indicators
QlikSense Buttons and Actions: the Dashboard that Runs the Meeting
SAP Business One Internal Reconciliation - featured image of the tutorial
SAP Business One Internal Reconciliation: Clear False Open Items

RELATED ARTICLES