SAP Business One RFM segmentation: three letters that solve a problem almost every sales committee has and very few look at head-on. A sales manager showed me his quarter close with the figure above budget and a calm face. Then I asked him for another list: the customers who bought from him last year and not this year. There were forty-three. Eleven were among his thirty best accounts from the prior year, and the aggregate covered up the leak because two large new customers offset the bleeding. The total was lying without stating a single false figure.
That is the blind spot this analysis attacks. Instead of looking at how much you sold, it looks at each customer through three signals: when they last bought from you (recency), how many times they bought (frequency) and for how much (monetary value). The method comes, in fact, from direct marketing in the nineties, when Arthur Hughes popularized it in Strategic Database Marketing to decide who to mail the printed catalog to (the acronym sounds like a German technical standard, but it is three columns of a table and nothing more). Today it serves to decide who your salesperson calls on Monday.

Why you need SAP Business One RFM segmentation in your sales management
Your ERP already has the data. Every sales invoice that gets posted leaves a date, a customer and an amount in OINV, and, likewise, every credit note does the same in ORIN. You have information to spare. What is missing is a standard report capable of answering who is leaving, because the out-of-the-box ones answer how much did we sell. As a result, the committee conversation always revolves around the same aggregate number.
Frederick Reichheld's work at Bain & Company put a number on something managers have always sensed: improving the retention rate by five points moves profits between 25% and 95%, depending on the industry. In other words, a customer rescued in time is worth quite a bit more than a new one won with a discount. Rescuing is also cheaper: the customer already knows your product, is already set up in the master data and already has negotiated commercial terms.
SAP Business One RFM segmentation turns that intuition into a list with names attached. As a result, the sales rep stops prioritizing by memory or by sympathy and starts prioritizing by observed behavior. That list does little filed away and a lot as input to a monthly management routine.
Prerequisites before writing the query
Before writing your first SAP Business One RFM segmentation query, go over these points. They are what make the result trustworthy on day one instead of on the third attempt.
- Read permissions on the tables
OINV,ORIN,OCRDandOCRG. A query profile is enough; you do not need write permissions. - Enough history: at least 24 months of invoicing loaded. With twelve months the analysis works, but frequency loses discriminating power.
- Clean business partner master data: duplicate customers split the history of a single company across two codes and ruin the quintiles.
- Clarity about currency: if you invoice in several currencies, decide from the start whether you will work in local or system currency.
- Access to Query Manager (Tools → Queries → Query Manager) or to SQL Server Management Studio / HANA Studio for testing.
One detail about the Query Manager worth knowing beforehand rather than afterward: in several versions it gets fussy with queries that start directly with WITH. In 9.3, if memory serves, the parser was even less tolerant than it is today. If it rejects the syntax you have two clean ways out: turn the CTEs into nested subqueries, or create the query as a view in the database and then call it from the Query Manager with a simple SELECT query. The second option is better, because it also leaves it reusable for Crystal Reports.
Step by step: build your SAP Business One RFM segmentation
Step 1. Define the window and build the net sales base
First, set the analysis period. Twenty-four months works well for businesses with recurring purchases; for project or machinery sales, on the other hand, it pays to stretch to 36 or 48. Then build a single base that adds invoices and subtracts credit notes, because a customer who returned half of what they bought is not worth the same as one who kept it all.
Here comes the first design annoyance: Document Total comes with the tax inside, so you have to subtract VatSum by hand to get to the net. And credit notes do not come with a negative sign; they live in a different table. Two minor details that, if you overlook them, inflate each customer's amount by 19% and leave chronic returners disguised as good customers.
Step 2. Calculate recency, frequency and monetary value
Then, with the base built, the calculation is an aggregation by customer. Recency is the number of days since the last invoice, frequency is the count of distinct invoices and monetary value is the net total for the period. Below, the first query in both dialects.
SQL Server
-- Base RFM metrics per customer (last 24 months)
SELECT
B.CardCode,
B.CardName,
DATEDIFF(DAY, MAX(B.DocDate), GETDATE()) AS Recency_Days,
COUNT(DISTINCT CASE WHEN B.Tipo = 'F' THEN B.DocEntry END) AS Frequency,
SUM(B.NetoDoc) AS Net_Amount
FROM (
SELECT T0.CardCode, T2.CardName, T0.DocEntry, T0.DocDate,
(T0.DocTotal - T0.VatSum) AS NetoDoc, 'F' AS Tipo
FROM OINV T0
INNER JOIN OCRD T2 ON T2.CardCode = T0.CardCode
WHERE T0.CANCELED = 'N'
AND T2.CardType = 'C'
AND T0.DocDate >= DATEADD(MONTH, -24, GETDATE())
UNION ALL
SELECT T1.CardCode, T3.CardName, T1.DocEntry, T1.DocDate,
-(T1.DocTotal - T1.VatSum) AS NetoDoc, 'N' AS Tipo
FROM ORIN T1
INNER JOIN OCRD T3 ON T3.CardCode = T1.CardCode
WHERE T1.CANCELED = 'N'
AND T3.CardType = 'C'
AND T1.DocDate >= DATEADD(MONTH, -24, GETDATE())
) B
GROUP BY B.CardCode, B.CardName
HAVING SUM(B.NetoDoc) > 0
ORDER BY Net_Amount DESC;
SAP HANA
-- Base RFM metrics per customer (last 24 months)
SELECT
B."CardCode",
B."CardName",
DAYS_BETWEEN(MAX(B."DocDate"), CURRENT_DATE) AS "Recency_Days",
COUNT(DISTINCT CASE WHEN B."Tipo" = 'F' THEN B."DocEntry" END) AS "Frequency",
SUM(B."NetoDoc") AS "Net_Amount"
FROM (
SELECT T0."CardCode", T2."CardName", T0."DocEntry", T0."DocDate",
(T0."DocTotal" - T0."VatSum") AS "NetoDoc", 'F' AS "Tipo"
FROM OINV T0
INNER JOIN OCRD T2 ON T2."CardCode" = T0."CardCode"
WHERE T0."CANCELED" = 'N'
AND T2."CardType" = 'C'
AND T0."DocDate" >= ADD_MONTHS(CURRENT_DATE, -24)
UNION ALL
SELECT T1."CardCode", T3."CardName", T1."DocEntry", T1."DocDate",
-(T1."DocTotal" - T1."VatSum") AS "NetoDoc", 'N' AS "Tipo"
FROM ORIN T1
INNER JOIN OCRD T3 ON T3."CardCode" = T1."CardCode"
WHERE T1."CANCELED" = 'N'
AND T3."CardType" = 'C'
AND T1."DocDate" >= ADD_MONTHS(CURRENT_DATE, -24)
) B
GROUP BY B."CardCode", B."CardName"
HAVING SUM(B."NetoDoc") > 0
ORDER BY "Net_Amount" DESC;
The filter CANCELED = 'N' seems like a minor detail and it has cost me dearly more than once: I presented a ranking where one account showed up as the most frequent of the year, and it turned out its frequency came from invoices cancelled and reissued because of tax-address errors. The rep in charge took the heat in the meeting over a customer who actually bought three times, not seventeen.
Step 3. Turn the metrics into quintiles with NTILE
The three metrics sit on incomparable scales: days, units and pesos. They therefore have to be brought to a common scale. The standard approach is to split the customer base into five equal-sized groups per metric and assign 1 to 5, where 5 is always the best. Likewise, the NTILE(5) function does exactly that and is available in both SQL Server and SAP HANA, according to the platform's window function documentation.
The direction of the sort matters more than it looks. For frequency and monetary value, more is better, so you sort ascending and quintile 5 ends up on top. For recency it is the other way around: fewer days since the last purchase is better, so you have to sort descending for the most recent customer to get a 5. Getting that direction wrong is the most common error and the quietest one, because the query runs just the same and returns a perfectly ordered ranking, backwards.
Step 4. Name the segments
A customer with R5-F5-M5 and another with R1-F5-M5 need opposite actions, even if their scores add up to something similar. So instead of handing the sales team three numbers, hand them a label that says what to do. Eight segments are more than enough to operate with.
- Champions (R≥4, F≥4, M≥4): they buy often, recently and in volume. Protect them and ask them for referrals.
- Loyal (R≥4, F≥3): stable base. Natural candidates for cross-selling.
- Cannot Lose Them (R≤2, M≥4): they spent a lot and disappeared. A call from the manager, not from the sales rep.
- At Risk (R=3, F≥3): they used to be regulars and they are cooling off. Here the intervention is still cheap.
- Dormant (R≤2, F≥3): they used to buy often and no longer do.
- New or Sporadic (R=5, F≤2): recent, with little history. They need a second purchase to consolidate.
- Lost (R≤2): no signs of life. Mass campaign, zero individual effort.
- Occasional: the rest of the customer base.

The complete SAP Business One RFM segmentation query
This is the final query. That is, it takes the base from step 2, applies the quintiles and returns the segment ready to export to Excel or feed a Crystal Report.
Dónde ejecutar este query. Úsalo en SQL Server Management Studio o en HANA Studio. El Generador de consultas de SAP Business One no siempre digiere las expresiones de tabla común (WITH), así que si necesitas el resultado dentro de B1, guarda la consulta como vista y llama a la vista desde el Generador.
SQL Server
WITH Ventas AS (
SELECT T0.CardCode, T0.DocEntry, T0.DocDate,
(T0.DocTotal - T0.VatSum) AS NetoDoc, 'F' AS Tipo
FROM OINV T0
WHERE T0.CANCELED = 'N'
AND T0.DocDate >= DATEADD(MONTH, -24, GETDATE())
UNION ALL
SELECT T1.CardCode, T1.DocEntry, T1.DocDate,
-(T1.DocTotal - T1.VatSum) AS NetoDoc, 'N' AS Tipo
FROM ORIN T1
WHERE T1.CANCELED = 'N'
AND T1.DocDate >= DATEADD(MONTH, -24, GETDATE())
),
Base AS (
SELECT V.CardCode,
DATEDIFF(DAY, MAX(V.DocDate), GETDATE()) AS Recencia,
COUNT(DISTINCT CASE WHEN V.Tipo = 'F' THEN V.DocEntry END) AS Frecuencia,
SUM(V.NetoDoc) AS Monto
FROM Ventas V
GROUP BY V.CardCode
HAVING SUM(V.NetoDoc) > 0
),
Quintiles AS (
SELECT B.*,
NTILE(5) OVER (ORDER BY B.Recencia DESC) AS R,
NTILE(5) OVER (ORDER BY B.Frecuencia ASC) AS F,
NTILE(5) OVER (ORDER BY B.Monto ASC) AS M
FROM Base B
)
SELECT
Q.CardCode AS [Code],
C.CardName AS [Customer],
ISNULL(G.GroupName, 'No group') AS [Group],
ISNULL(S.SlpName, 'Unassigned') AS [Sales Employee],
Q.Recencia AS [Days Since Purchase],
Q.Frecuencia AS [Invoices],
Q.Monto AS [Net Sales],
Q.R, Q.F, Q.M,
CAST(Q.R AS VARCHAR(1)) + CAST(Q.F AS VARCHAR(1)) + CAST(Q.M AS VARCHAR(1)) AS [RFM Code],
CASE
WHEN Q.R >= 4 AND Q.F >= 4 AND Q.M >= 4 THEN 'Champions'
WHEN Q.R <= 2 AND Q.M >= 4 THEN 'Cannot Lose Them'
WHEN Q.R >= 4 AND Q.F >= 3 THEN 'Loyal'
WHEN Q.R = 3 AND Q.F >= 3 THEN 'At Risk'
WHEN Q.R <= 2 AND Q.F >= 3 THEN 'Dormant'
WHEN Q.R = 5 AND Q.F <= 2 THEN 'New or Sporadic'
WHEN Q.R <= 2 THEN 'Lost'
ELSE 'Occasional'
END AS [Segment]
FROM Quintiles Q
INNER JOIN OCRD C ON C.CardCode = Q.CardCode
LEFT JOIN OCRG G ON G.GroupCode = C.GroupCode
LEFT JOIN OSLP S ON S.SlpCode = C.SlpCode
WHERE C.CardType = 'C'
ORDER BY Q.Monto DESC;
SAP HANA
WITH "Ventas" AS (
SELECT T0."CardCode", T0."DocEntry", T0."DocDate",
(T0."DocTotal" - T0."VatSum") AS "NetoDoc", 'F' AS "Tipo"
FROM OINV T0
WHERE T0."CANCELED" = 'N'
AND T0."DocDate" >= ADD_MONTHS(CURRENT_DATE, -24)
UNION ALL
SELECT T1."CardCode", T1."DocEntry", T1."DocDate",
-(T1."DocTotal" - T1."VatSum") AS "NetoDoc", 'N' AS "Tipo"
FROM ORIN T1
WHERE T1."CANCELED" = 'N'
AND T1."DocDate" >= ADD_MONTHS(CURRENT_DATE, -24)
),
"Base" AS (
SELECT V."CardCode",
DAYS_BETWEEN(MAX(V."DocDate"), CURRENT_DATE) AS "Recencia",
COUNT(DISTINCT CASE WHEN V."Tipo" = 'F' THEN V."DocEntry" END) AS "Frecuencia",
SUM(V."NetoDoc") AS "Monto"
FROM "Ventas" V
GROUP BY V."CardCode"
HAVING SUM(V."NetoDoc") > 0
),
"Quintiles" AS (
SELECT B."CardCode", B."Recencia", B."Frecuencia", B."Monto",
NTILE(5) OVER (ORDER BY B."Recencia" DESC) AS "R",
NTILE(5) OVER (ORDER BY B."Frecuencia" ASC) AS "F",
NTILE(5) OVER (ORDER BY B."Monto" ASC) AS "M"
FROM "Base" B
)
SELECT
Q."CardCode" AS "Code",
C."CardName" AS "Customer",
IFNULL(G."GroupName", 'No group') AS "Group",
IFNULL(S."SlpName", 'Unassigned') AS "Sales Employee",
Q."Recencia" AS "Days Since Purchase",
Q."Frecuencia" AS "Invoices",
Q."Monto" AS "Net Sales",
Q."R", Q."F", Q."M",
TO_VARCHAR(Q."R") || TO_VARCHAR(Q."F") || TO_VARCHAR(Q."M") AS "RFM Code",
CASE
WHEN Q."R" >= 4 AND Q."F" >= 4 AND Q."M" >= 4 THEN 'Champions'
WHEN Q."R" <= 2 AND Q."M" >= 4 THEN 'Cannot Lose Them'
WHEN Q."R" >= 4 AND Q."F" >= 3 THEN 'Loyal'
WHEN Q."R" = 3 AND Q."F" >= 3 THEN 'At Risk'
WHEN Q."R" <= 2 AND Q."F" >= 3 THEN 'Dormant'
WHEN Q."R" = 5 AND Q."F" <= 2 THEN 'New or Sporadic'
WHEN Q."R" <= 2 THEN 'Lost'
ELSE 'Occasional'
END AS "Segment"
FROM "Quintiles" Q
INNER JOIN OCRD C ON C."CardCode" = Q."CardCode"
LEFT JOIN OCRG G ON G."GroupCode" = C."GroupCode"
LEFT JOIN OSLP S ON S."SlpCode" = C."SlpCode"
WHERE C."CardType" = 'C'
ORDER BY Q."Monto" DESC;
Look at the order of the WHEN: the «Cannot Lose Them» condition comes before the «Loyal» one on purpose, because a CASE evaluates top to bottom and stops at the first match. If you move that line further down, your large accounts on their way out will hide inside another segment and nobody will call them.
Variations and use cases
The previous query gives you the detail. For the management meeting, however, the summary is more useful: how many customers are in each segment and how much revenue they represent. So wrap the full query as a subquery and group by segment.
SQL Server
-- Executive summary by segment (uses the full query as a subquery)
SELECT
R.Segmento,
COUNT(*) AS Customers,
SUM(R.Monto) AS Net_Sales,
CAST(100.0 * SUM(R.Monto) / SUM(SUM(R.Monto)) OVER () AS DECIMAL(5,2)) AS Pct_Sales,
AVG(R.Recencia) AS Avg_Days_Since_Purchase
FROM ( /* the full query from the previous block goes here, without ORDER BY */ ) R
GROUP BY R.Segmento
ORDER BY Net_Sales DESC;
SAP HANA
-- Executive summary by segment (uses the full query as a subquery)
SELECT
R."Segmento",
COUNT(*) AS "Customers",
SUM(R."Monto") AS "Net_Sales",
ROUND(100.0 * SUM(R."Monto") / SUM(SUM(R."Monto")) OVER (), 2) AS "Pct_Sales",
AVG(R."Recencia") AS "Avg_Days_Since_Purchase"
FROM ( /* the full query from the previous block goes here, without ORDER BY */ ) R
GROUP BY R."Segmento"
ORDER BY "Net_Sales" DESC;
From that base, SAP Business One RFM segmentation supports three concrete uses. First, RFM by business line: add a filter by item group by joining with INV1 and OITM, and you will find that a customer can be a champion in one category and lost in another. Second, RFM compared against the previous quarter: save the result in a user-defined table every month and watch the migrations between segments, which is where the real signal is. Third, automatic alert: if a customer moves from «Loyal» to «At Risk», fire a notification to the sales rep through the system's alert management.

Best practices and common mistakes
Segment within comparable portfolios. SAP Business One RFM segmentation over a mixed portfolio misleads. If you mix retail and wholesale distributors in the same portfolio, the monetary quintiles get captured by the wholesalers and all of retail falls into quintile 1. For example, in a company with a direct channel and a distributor channel, run the query separately for each channel using OCRD.GroupCode as a filter.
Watch out for the customer with one huge invoice. That one-off project from twenty-two months ago, for instance, leaves them with M5 and F1, and the resulting label misleads. A minimum threshold of two invoices to enter the analysis tidies up the picture quite a bit.
Fit the window to your real purchase cycle. Twenty-four months is a reasonable default, not a law. If your typical customer buys every fifteen days, 24 months dilutes the recency signal; if, on the other hand, you sell equipment replaced every three years, a short window will flag perfectly healthy customers as lost.
Do not run this on the production database during business hours. With portfolios of more than twenty thousand business partners and several years of invoicing, window functions are heavy. Better to schedule it at night or point it at a replica.
Multicurrency. If you invoice in dollars and in pesos, replace DocTotal - VatSum by DocTotalSy - VatSumSy to express everything in system currency. Otherwise you will be adding apples and oranges and the monetary quintile is useless.
Deliver the list, not the report. A file with eight segments and five hundred customers does not act on itself. What works instead is handing each rep their twenty at-risk accounts with the phone number next to them, and reviewing at the next meeting what happened with each one.
Official SAP Resources
- SAP Help Portal – SAP Business One Documentation: manuals by version, including working with queries and the Query Manager.
- SAP HANA – Window Functions and the Window Specification: official syntax for
NTILEand the rest of the window functions. - SAP Community – SAP Business One: forums where variations of these queries and version-specific quirks are discussed.
Conclusion: SAP Business One RFM segmentation as a monthly routine
What is valuable about SAP Business One RFM segmentation is not the query. It is the conversation it enables, because it forces the sales team to talk about specific customers instead of attainment percentages, and it turns a discussion about the past into a call list for next week. In fact, the first time you run it you will find accounts you thought were active that have not bought from you in eight months. It almost always happens.
Finally, my practical recommendation: save the query as a view, schedule it monthly and review it in the sales committee alongside the traditional sales report. Two numbers side by side. One tells you how you did and the other tells you what is going to happen.
If this job sounds familiar and you want the rest of the practical SAP Business One queries and tutorials, in the Strategic Circle I publish a new tutorial every two days, with the full SQL for SQL Server and HANA ready to paste into your Query Manager.




