SQL Queries for Sales Analysis by Salesperson in SAP Business One - featured image

Publications

SQL Queries for Sales Analysis by Salesperson in SAP Business One

Hector Pincheira

Hector Pincheira

CIO | CTO
Digital Strategy & Technology Innovation

items

How many times has the sales manager asked you to know exactly how much each sales rep sold, with real margins and compared against the previous period? In most companies running SAP Business One, that answer arrives late, built by hand in a spreadsheet or simply incomplete. In this tutorial you will learn to create SQL queries for sales analysis by salesperson in SAP Business One, ready to run in Query Manager on both SQL Server and SAP HANA.

SAP Business One sales by sales rep - commercial metrics analysis
Sales analysis by sales rep turns ERP data into concrete commercial decisions

Why Doesn't SAP B1 Solve It «Out of the Box»?

SAP Business One includes standard sales reports, but as a consequence of its transaction-oriented architecture, management analyses that combine volume, margin, period and sales rep in a single view require custom SQL. The native sales-by-rep report does not include direct gross margin, nor does it allow period-over-period comparisons with a single click.

SAP B1, however, stores all that information in well-structured tables. The key is the SlpCode, present in every sales document, which links each transaction to the OSLP (Sales Employees). So with the right queries you can build any analysis your commercial team needs, without extra tools or manual exports.

Why Do You Need This Analysis in Your Company?

The SAP Business One sales by sales rep analysis is fundamental to three decisions that directly impact your company's profitability:

  • Calculate commissions with exact ERP data, eliminating the disputes that arise from manual versions or outdated figures.
  • Detect the classic problem of uncontrolled discounts: sales reps with high volume but low margin, who are actually eroding profitability instead of generating it.
  • Monitor the active pipeline: open sales orders not yet invoiced that represent revenue in progress.

That way commercial analysis stops being a monthly data-consolidation exercise and becomes a weekly decision tool. And because the data comes straight from the ERP, it removes the subjectivity that normally surrounds commercial performance reviews.

Prerequisites

Before running the queries, check the following points:

  • Access to Query Manager in SAP B1: Tools → Queries → Query Manager.
  • Sales documents must have a value in the field Seller (SlpCode). If that field is empty in historical documents, the results will be incomplete.
  • Read permissions on the tables: OSLP, OINV, INV1, ORDER, RDR1, OITM, OITB.
  • In SAP HANA, confirm the company schema name (usually SBO_[company]) and use double quotes for all field names.

Key Tables for Sales-by-Rep Analysis in SAP B1

Below are the tables we will use in all the queries in this tutorial:

TableDescriptionKey fields
OSLPSales reps / Sales employeesSlpCode, SlpName, Commission
OINVCustomer invoices (header)SlpCode, DocTotalSy, GrosProfit, Document Date
INV1Customer invoice linesLine Total, GrossBuyPr, Quantity
ORDERSales orders (header)SlpCode, Document Status, DocDueDate
OITMitemsItemCode, ItmsGrpCod
OITBItem groupsItmsGrpCod, Item Group Name

Query 1: Total Sales by Sales Rep in a Period

This is the base query and the most requested one. It shows the total invoiced per sales rep (customer invoices in Open or Closed status, excluding cancelled ones) in a date range you enter as a parameter. It also includes the number of unique customers served and the gross margin calculated from the document header.

SQL Server

-- Sales by Sales Rep for Period | SQL Server
-- Parameters: [%0] Start Date, [%1] End Date
SELECT
    S.SlpCode                        AS [Code],
    S.SlpName                        AS [Sales Rep],
    COUNT(DISTINCT T.CardCode)       AS [Unique Customers],
    COUNT(DISTINCT T.DocNum)         AS [Invoice Count],
    SUM(T.DocTotalSy)                AS [Total Sales LC],
    SUM(T.GrosProfit)                AS [Gross Profit],
    CASE
        WHEN SUM(T.DocTotalSy) > 0
        THEN ROUND(SUM(T.GrosProfit) / SUM(T.DocTotalSy) * 100, 2)
        ELSE 0
    END                              AS [Margin %]
FROM OINV T
INNER JOIN OSLP S ON T.SlpCode = S.SlpCode
WHERE T.DocDate BETWEEN '[%0]' AND '[%1]'
  AND T.CANCELED = 'N'
GROUP BY S.SlpCode, S.SlpName
ORDER BY [Total Sales LC] DESC

SAP HANA

-- Sales by Sales Rep for Period | SAP HANA
-- Parameters: [%0] Start Date, [%1] End Date
SELECT
    S."SlpCode"                          AS "Code",
    S."SlpName"                          AS "Sales Rep",
    COUNT(DISTINCT T."CardCode")         AS "Unique Customers",
    COUNT(DISTINCT T."DocNum")           AS "Invoice Count",
    SUM(T."DocTotalSy")                  AS "Total Sales LC",
    SUM(T."GrosProfit")                  AS "Gross Profit",
    CASE
        WHEN SUM(T."DocTotalSy") > 0
        THEN ROUND(SUM(T."GrosProfit") / SUM(T."DocTotalSy") * 100, 2)
        ELSE 0
    END                                  AS "% Margin"
FROM OINV T
INNER JOIN OSLP S ON T."SlpCode" = S."SlpCode"
WHERE T."DocDate" BETWEEN '[%0]' AND '[%1]'
  AND T."CANCELED" = 'N'
GROUP BY S."SlpCode", S."SlpName"
ORDER BY "Total Sales LC" DESC

Technical note: The field DocTotalSy stores the total converted to the system local currency, which guarantees comparability in companies that issue invoices in several currencies. The field GrosProfit in the OINV header is the sum of the margins calculated on each line at the time of invoicing.

SAP Business One sales by sales rep - analysis in Query Manager
The SAP B1 Query Manager lets you run these queries and save them for recurring use by the sales team

Query 2: Sales Compared to the Same Period Last Year

For example, the sales manager needs to see in a single table how much each rep sold this month versus the same month last year. Building that comparison by hand in Excel, however, means cross-referencing two separate files. This query solves it in a single run:

SQL Server

-- Sales by Sales Rep Comparison: Current Month vs. Same Month Last Year | SQL Server
SELECT
    S.SlpName                        AS [Sales Rep],
    SUM(CASE
        WHEN YEAR(T.DocDate) = YEAR(GETDATE()) AND MONTH(T.DocDate) = MONTH(GETDATE())
        THEN T.DocTotalSy ELSE 0 END) AS [Current Month],
    SUM(CASE
        WHEN YEAR(T.DocDate) = YEAR(GETDATE()) - 1 AND MONTH(T.DocDate) = MONTH(GETDATE())
        THEN T.DocTotalSy ELSE 0 END) AS [Same Month Prior Yr.],
    ROUND(
        (SUM(CASE WHEN YEAR(T.DocDate) = YEAR(GETDATE()) AND MONTH(T.DocDate) = MONTH(GETDATE())
                  THEN T.DocTotalSy ELSE 0 END)
         - SUM(CASE WHEN YEAR(T.DocDate) = YEAR(GETDATE()) - 1 AND MONTH(T.DocDate) = MONTH(GETDATE())
                    THEN T.DocTotalSy ELSE 0 END))
        / NULLIF(SUM(CASE WHEN YEAR(T.DocDate) = YEAR(GETDATE()) - 1 AND MONTH(T.DocDate) = MONTH(GETDATE())
                          THEN T.DocTotalSy ELSE 0 END), 0) * 100
    , 2)                             AS [Variance %]
FROM OINV T
INNER JOIN OSLP S ON T.SlpCode = S.SlpCode
WHERE T.CANCELED = 'N'
  AND YEAR(T.DocDate) IN (YEAR(GETDATE()), YEAR(GETDATE()) - 1)
  AND MONTH(T.DocDate) = MONTH(GETDATE())
GROUP BY S.SlpName
ORDER BY [Current Month] DESC

SAP HANA

-- Sales by Sales Rep Comparison: Current Month vs. Same Month Last Year | SAP HANA
SELECT
    S."SlpName"                       AS "Sales Rep",
    SUM(CASE
        WHEN YEAR(T."DocDate") = YEAR(CURRENT_DATE) AND MONTH(T."DocDate") = MONTH(CURRENT_DATE)
        THEN T."DocTotalSy" ELSE 0 END) AS "Current Month",
    SUM(CASE
        WHEN YEAR(T."DocDate") = YEAR(CURRENT_DATE) - 1 AND MONTH(T."DocDate") = MONTH(CURRENT_DATE)
        THEN T."DocTotalSy" ELSE 0 END) AS "Same Month Prior Yr.",
    ROUND(
        (SUM(CASE WHEN YEAR(T."DocDate") = YEAR(CURRENT_DATE) AND MONTH(T."DocDate") = MONTH(CURRENT_DATE)
                  THEN T."DocTotalSy" ELSE 0 END)
         - SUM(CASE WHEN YEAR(T."DocDate") = YEAR(CURRENT_DATE) - 1 AND MONTH(T."DocDate") = MONTH(CURRENT_DATE)
                    THEN T."DocTotalSy" ELSE 0 END))
        / NULLIF(SUM(CASE WHEN YEAR(T."DocDate") = YEAR(CURRENT_DATE) - 1 AND MONTH(T."DocDate") = MONTH(CURRENT_DATE)
                          THEN T."DocTotalSy" ELSE 0 END), 0) * 100
    , 2)                              AS "Variance %"
FROM OINV T
INNER JOIN OSLP S ON T."SlpCode" = S."SlpCode"
WHERE T."CANCELED" = 'N'
  AND YEAR(T."DocDate") IN (YEAR(CURRENT_DATE), YEAR(CURRENT_DATE) - 1)
  AND MONTH(T."DocDate") = MONTH(CURRENT_DATE)
GROUP BY S."SlpName"
ORDER BY "Current Month" DESC

Query 3: Gross Margin by Sales Rep and Item Group

This query drills down to the line level to analyze margin by sales rep and product category. You will see that the analysis reveals patterns the total sales report hides: first, which rep gets the better margin on each product family, and second, where discounts are being applied that erode profitability. As a result, you can make far more surgical decisions on pricing and authorized discounts.

SQL Server

-- Margin by Sales Rep and Item Group | SQL Server
-- Parameters: [%0] Start Date, [%1] End Date
SELECT
    S.SlpName                                           AS [Sales Rep],
    G.ItmsGrpNam                                        AS [Item Group],
    SUM(L.LineTotal)                                    AS [Net Sales],
    SUM(L.GrossBuyPr * L.Quantity)                      AS [Total Cost],
    SUM(L.LineTotal) - SUM(L.GrossBuyPr * L.Quantity)   AS [Gross Margin],
    CASE
        WHEN SUM(L.LineTotal) > 0
        THEN ROUND(
            (SUM(L.LineTotal) - SUM(L.GrossBuyPr * L.Quantity))
            / SUM(L.LineTotal) * 100, 2)
        ELSE 0
    END                                                 AS [% Margin]
FROM OINV T
INNER JOIN INV1 L  ON T.DocEntry = L.DocEntry
INNER JOIN OSLP S  ON T.SlpCode  = S.SlpCode
INNER JOIN OITM I  ON L.ItemCode = I.ItemCode
INNER JOIN OITB G  ON I.ItmsGrpCod = G.ItmsGrpCod
WHERE T.DocDate BETWEEN '[%0]' AND '[%1]'
  AND T.CANCELED = 'N'
  AND L.LineStatus != 'C'
GROUP BY S.SlpName, G.ItmsGrpNam
ORDER BY S.SlpName, [% Margin] DESC

SAP HANA

-- Margin by Sales Rep and Item Group | SAP HANA
-- Parameters: [%0] Start Date, [%1] End Date
SELECT
    S."SlpName"                                              AS "Sales Rep",
    G."ItmsGrpNam"                                           AS "Item Group",
    SUM(L."LineTotal")                                       AS "Net Sales",
    SUM(L."GrossBuyPr" * L."Quantity")                       AS "Total Cost",
    SUM(L."LineTotal") - SUM(L."GrossBuyPr" * L."Quantity")  AS "Gross Margin",
    CASE
        WHEN SUM(L."LineTotal") > 0
        THEN ROUND(
            (SUM(L."LineTotal") - SUM(L."GrossBuyPr" * L."Quantity"))
            / SUM(L."LineTotal") * 100, 2)
        ELSE 0
    END                                                      AS "% Margin"
FROM OINV T
INNER JOIN INV1 L  ON T."DocEntry" = L."DocEntry"
INNER JOIN OSLP S  ON T."SlpCode"  = S."SlpCode"
INNER JOIN OITM I  ON L."ItemCode" = I."ItemCode"
INNER JOIN OITB G  ON I."ItmsGrpCod" = G."ItmsGrpCod"
WHERE T."DocDate" BETWEEN '[%0]' AND '[%1]'
  AND T."CANCELED" = 'N'
  AND L."LineStatus" != 'C'
GROUP BY S."SlpName", G."ItmsGrpNam"
ORDER BY S."SlpName", "% Margin" DESC

Important detail: The field GrossBuyPr in INV1 stores the item unit cost at the exact moment the invoice was created. If your company uses weighted average valuation, that value reflects the average in force on that date. It is therefore the right cost for historical profitability analysis, even if it differs from the current cost of the item.

Query 4: Active Pipeline — Open Sales Orders by Sales Rep

This analysis answers a question few managers can answer clearly: how much does each rep have in process that has not been invoiced yet? Knowing the active pipeline lets you project the month-end close before the month is over. SAP B1 has no native pipeline-by-rep report with a total amount; this query builds it straight from the open sales orders.

SQL Server

-- Active Pipeline by Sales Rep (Open Sales Orders) | SQL Server
SELECT
    S.SlpName                           AS [Sales Rep],
    COUNT(DISTINCT T.DocNum)            AS [Open Orders],
    COUNT(DISTINCT T.CardCode)          AS [Customers],
    SUM(T.DocTotal)                     AS [Pipeline Amount],
    MIN(T.DocDueDate)                   AS [Earliest Delivery],
    MAX(T.DocDueDate)                   AS [Latest Delivery],
    DATEDIFF(DAY, MIN(T.DocDate), GETDATE()) AS [Days Oldest SO]
FROM ORDR T
INNER JOIN OSLP S ON T.SlpCode = S.SlpCode
WHERE T.DocStatus = 'O'
  AND T.CANCELED  = 'N'
GROUP BY S.SlpName
ORDER BY [Pipeline Amount] DESC

SAP HANA

-- Active Pipeline by Sales Rep (Open Sales Orders) | SAP HANA
SELECT
    S."SlpName"                          AS "Sales Rep",
    COUNT(DISTINCT T."DocNum")           AS "Open Orders",
    COUNT(DISTINCT T."CardCode")         AS "Customers",
    SUM(T."DocTotal")                    AS "Pipeline Amount",
    MIN(T."DocDueDate")                  AS "Earliest Delivery",
    MAX(T."DocDueDate")                  AS "Latest Delivery",
    DAYS_BETWEEN(MIN(T."DocDate"), CURRENT_DATE) AS "Days Oldest SO"
FROM ORDR T
INNER JOIN OSLP S ON T."SlpCode" = S."SlpCode"
WHERE T."DocStatus" = 'O'
  AND T."CANCELED"  = 'N'
GROUP BY S."SlpName"
ORDER BY "Pipeline Amount" DESC
SAP Business One sales by sales rep - commercial pipeline metrics
Active pipeline by sales rep is one of the most valuable indicators for projecting the month-end close

Variations and Advanced Use Cases

The four queries above are the solid base of commercial analysis. Your operation, however, may call for specific extensions. Here are the most frequent cases:

  • Include credit notes in net sales: To calculate net commissions, you have to subtract credit notes from the total invoiced. Add a LEFT JOIN ORIN NC ON NC.SlpCode = T.SlpCode AND NC.DocDate BETWEEN ... AND NC.CANCELED = 'N' and subtract SUM(NC.DocTotalSy) from the sales total.
  • Calculate commission directly in the query: If the OSLP table has the field Commission (percentage) configured, you can add SUM(T.DocTotalSy) * S.Commission / 100 AS [Calculated Commission] directly to Query 1.
  • Segment by geographic zone: If your customers have the Territory field assigned (OCRD.Territory), you can add an INNER JOIN OCRD C ON T.CardCode = C.CardCode and group by zone as well, to analyze sales by rep and region.
  • Year-to-date comparison (YTD): Replace the month filter with YEAR(T.DocDate) = YEAR(GETDATE()) to get the current year-to-date versus the prior year across all sales reps.

Best Practices and Common Mistakes

After implementing these queries in a number of companies running SAP Business One, there are mistakes that show up systematically. Better to know them before you run anything:

  • Mistake 1 — Not filtering cancelled invoices. Always include AND T.CANCELED = 'N'. Without that condition, the amounts will come out inflated, because SAP B1 keeps cancelled documents in the same tables with their original total.
  • Mistake 2 — SlpCode = -1. Documents with no sales rep assigned carry SlpCode = -1, which in OSLP corresponds to the dummy record «No Sales Rep». If you use INNER JOIN, those documents drop out of the analysis silently. Consider adding AND T.SlpCode != -1 to exclude them explicitly, or Left Join if you want to see them.
  • Mistake 3 — Confusing DocTotal with DocTotalSy. In multi-currency companies, Document Total is the amount in the document currency (which may be USD or EUR), while DocTotalSy is the equivalent in local currency. To compare reps operating in different currencies, always use DocTotalSy.
  • Best practice — Protect access. Save these queries under a «Sales Analysis» category in the Query Manager and restrict access through SAP B1 authorizations (Administration → Authorizations → General Authorizations). That way only the sales manager and senior management can run them.
  • Best practice — Schedule it as an alert. You can set these queries up in the SAP B1 Alerts module so they go out automatically every Monday, delivering the weekly sales-by-rep summary without anyone having to run it by hand.

Official SAP Resources

To go deeper into the Query Manager and the SAP Business One tables, these are the most useful resources:

  • SAP Business One Help Portal: official documentation with the complete dictionary of tables and fields.
  • SAP Community — Business One: forum with thousands of threads on SQL queries and sales analysis.
  • SAP Business One SDK Help: available from the Help menu inside SAP B1, it holds the complete database reference with every field and its description.

Conclusion: From ERP to Sales Dashboard in Minutes

The SAP Business One sales by sales rep requires no additional tools and no complex integrations. The information is already in your ERP; you just need the right queries to pull it out in a structured way. In under 15 minutes you can have four reports that replace hours of manual work in Excel, with data straight from the source.

These queries are the starting point, though, not the destination. The next level is embedding them in a Business Intelligence dashboard where managers can explore the data visually and dynamically, without running queries by hand. That multiplies the value: ERP data becomes a continuous decision asset instead of a one-off report.

If you are a member of Strategic Circle, you get access to extended versions of these queries, including automatic commission calculation with credit notes and returns netted out, plus the ready-to-use Crystal Reports version. If you are not a member yet, learn about the benefits of the Círculo Estratégico here and get access to every PRO-level SAP Business One tutorial.

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