Usina BRAdvPL Guide
Sign in
← All topics
PRACTICAL GUIDEUnder review

JOINs and aggregate functions in Protheus

SELECT ... LEFT JOIN ... ON ... GROUP BY ...

Joins tables and aggregates results while preserving branch context.

JOINs and aggregate functions in ProtheusAdvPL
01 · OVERVIEW

Overview

JOIN defines key matching; GROUP BY groups rows and COUNT/SUM calculate per-group values. A 1:N relationship can multiply rows and distort header totals. For LEFT JOIN, evaluate optional-table filters in ON when unmatched records must remain. This example builds a SQL string without executing it. Branch and logical-deletion filters apply independently to each table. The community reference illustrates JOIN and aggregation, but its general NOLOCK advice and direct writes are not adopted. (Sources: refs. 1–2.)

02 · SYNTAX

Syntax

SELECT ... LEFT JOIN ... ON ... GROUP BY ...
03 · PRACTICAL EXAMPLE

Commented example

#Include "Protheus.ch"

User Function Ed500()
    Local cSql := "SELECT A.A1_COD,A.A1_LOJA,COUNT(P.C5_NUM) AS QTD "
    // Filter each table according to its sharing settings.
    cSql += "FROM "+RetSqlName("SA1")+" A "
    cSql += "LEFT JOIN "+RetSqlName("SC5")+" P ON "
    cSql += "P.C5_CLIENTE=A.A1_COD AND P.C5_LOJACLI=A.A1_LOJA "
    cSql += "AND P.C5_FILIAL='"+xFilial("SC5")+"' "
    cSql += "AND P.D_E_L_E_T_=' ' "
    cSql += "WHERE A.A1_FILIAL='"+xFilial("SA1")+"' "
    cSql += "AND A.D_E_L_E_T_=' ' "
    cSql += "GROUP BY A.A1_COD,A.A1_LOJA"
    ConOut(cSql)
Return Nil
Expected result

Displays SQL counting orders by customer/store, including groups without orders; opens no cursor. Under review: editorial example neither compiled nor run in Protheus. Check includes, release, RDD and context before testing.

BEST PRACTICES
  • Before execution, validate dictionary, permissions, cardinality, ChangeQuery, types and plan. For external values, use framework parameters rather than concatenation.
  • Under review: editorial example neither compiled nor run in Protheus. Check includes, release, RDD and context before testing.

Related content

REFERENCES
  1. TOTVS. Desenvolvendo queries no Protheus — seções de suporte SQL. TDN. Accessed on 2026-10-27.
  2. thalysjuvenal/advpl-specialist. embedded-sql/reference.md; commit d80599b. Accessed on 2026-10-27.
Status
Under review
Page created on
Last reviewed on
Original language
Portuguese
Reviewed by
Usina.BR
0 approved comment(s)

Comments

There are no approved comments yet.

Sign in with Google or Microsoft to comment.

Powered by Usina Docs · Alpha