Using Aggregate function to fetch values from different tables in SAP

When working with SAP databases, you often need to retrieve data from multiple related tables while handling duplicate or varying descriptions for the same entity. Aggregate functions provide an effective solution for consolidating data and selecting specific values when joins result in multiple records.

If your query returns different descriptions for the same fund and you want to keep any one description, you can use aggregation functions like MIN() or MAX() to select a single value from the duplicates.

Using MIN() Aggregate Function

The following example demonstrates how to use the MIN() aggregate function to fetch fund information while handling multiple descriptions ?

SELECT
    X1."FundName"
    ,MIN(X0."Description") AS "Description"
    ,X0."FundId"
FROM INV1 X0
INNER JOIN OINV X1 ON X0."FundId" = X1."FundId"
INNER JOIN NNM1 X2 ON X1."SourceId" = X2."SourceId"
WHERE X1."FundTotal" > 1000
AND X0."FundStart" BETWEEN [%1] AND [%2]
GROUP BY X1."FundName", X0."FundId"

Query Breakdown

This query performs the following operations ?

  • JOIN Operations: Links three tables (INV1, OINV, NNM1) using FundId and SourceId relationships
  • WHERE Clause: Filters records where FundTotal exceeds 1000 and FundStart falls within specified date parameters
  • GROUP BY: Groups results by FundName and FundId to eliminate duplicates
  • MIN() Function: Selects the alphabetically smallest description when multiple descriptions exist for the same fund

Alternative Aggregate Functions

You can replace MIN() with other aggregate functions based on your requirements ?

-- To get the maximum description value
,MAX(X0."Description") AS "Description"

-- To count different descriptions
,COUNT(DISTINCT X0."Description") AS "DescriptionCount"

-- To get the first non-null description
,FIRST_VALUE(X0."Description") AS "Description"

Conclusion

Aggregate functions like MIN(), MAX(), and COUNT() are essential tools for handling duplicate data when joining multiple tables in SAP, allowing you to consolidate results and select specific values from grouped records.

Updated on: 2026-03-13T18:02:36+05:30

377 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements