LWC Lightning Datatable with Aggregated Columns

In Salesforce LWC lightning data tables, we can add aggregate columns to display aggregated values, such as the sum of a number of records and an average of amounts in the currency field.

In this Salesforce tutorial, we will learn how to create an LWC lightning data table with aggregated columns.

Create LWC Lightning Datatable with Aggregated Columns in Salesforce

In the steps below, we will create an LWC data table that will display the account records, and in the aggregate column, we will display the total number (sum) of contacts related to the account in the specific row.

  1. Create the controller class that will fetch the account records. In this, we have fetched the account details such as name, industry, and type of accounts with their related contacts.

This data is fetched from the Contact object using the Account-Contact relationship.

public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<AggregateResult> getAccountData() {
        return [SELECT Account.Name accountName,
                Account.Industry industry,
                Account.Type type,
                COUNT(Contact.Id) contactCount
                FROM Contact
                GROUP BY Account.Name, Account.Industry, Account.Type
                HAVING COUNT(Contact.Id) > 1];
    }
}

Using the count function “COUNT(Contact.Id)“, we will sum the number of contacts related to each account, referring to the contact ID.

  1. Enter the code below in the HTML file to render the UI of the LWC data table.
<template>
    <lightning-card title="Account Contact Aggregates" icon-name="standard:account">
        <div class="slds-m-around_medium">
            <lightning-datatable
                key-field="id"
                data={accountData}
                columns={columns}
                hide-checkbox-column>
            </lightning-datatable>
        </div>
    </lightning-card>
</template>
  1. After this, enter the code below in the JS file to define the logic of displaying the count of contacts related to each account in the table.

The aggregate method (count) is already defined in the controller class, so we just need to define the columns to render in the table.

import { LightningElement, track, wire } from 'lwc';
import getAccountData from '@salesforce/apex/AccountController.getAccountData';

export default class AccountDataTable extends LightningElement {
    @track accountData = [];
    @track columns = [
        { label: 'Account Name', fieldName: 'accountName', type: 'text' },
        { label: 'Industry', fieldName: 'industry', type: 'text' },
        { label: 'Type', fieldName: 'type', type: 'text' },
        { label: 'Contact Count', fieldName: 'contactCount', type: 'number' }
    ];

    @wire(getAccountData)
    wiredAccountData({ data, error }) {
        if (data) {
            this.accountData = data.map((record, index) => {
                return {
                    id: 'row-' + index,
                    accountName: record.accountName,
                    industry: record.industry,
                    type: record.type,
                    contactCount: record.contactCount
                };
            });
        } else if (error) {
            console.error('Error:', error);
        }
    }
}

In the above code, the columns array sets column labels, field names, and data types. The @wire decorator fetches apex data, and the wiredAccountData function processes it, mapping each record to a data table format with a unique ID and matching field values to column values.

Also, ensure that the aggregate column “type” is a number, not text.

  1. Make the component visible to the Lightning page by entering the code below inside the LightningComponentBundle tag.
<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
  1. Deploy the LWC component to the Lightning page. There, you will see the aggregate column Contact Count displaying the total number of contacts for each account in the row.
Add Aggregate Columns in LWC data table

This way, we can create an LWC lightning data table with aggregated columns by following the steps above.

Conclusion

In this Salesforce tutorial, we have learned how to create an LWC lightning data table with aggregate columns. In the above example, we have displayed the sum of the number of contacts related to a specific account in the aggregated column.

The logic for getting the aggregate data is defined in the Controller class to count the number of records. Following the above steps, you will be able to create a Salesforce Lightning data table with an aggregate column.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.