% This file is embedded in datatool-user.pdf version 3.4.5 2026-08-23
% Example 85 Displaying Data with Calculations, Filtering and Row Highlighting
% Label: "ex:displaydbaverages"
% arara: pdflatex
% arara: pdfcrop
\documentclass[12pt]{article}
\pagestyle{empty}
 \begin{filecontents}[noheader,overwrite]{studentmarks.csv}
Surname,Forename,StudentNo,Assign1,Assign2,Assign3
"Smith, Jr",John,102689,68,57,72
"Brown",Jane,102647,75,84,80
"Brown",Jane,102646,64,92,79
"Brown",Andy,103569,42,52,54
"Adams",Zoë,105987,52,48,57
"Brady",Roger,106872,68,60,62
"Verdon",Clare,104356,45,50,48
\end{filecontents}

\usepackage{colortbl}
\usepackage{datatool}
\DTLsetup{store-datum,default-name=marks}
\DTLread{studentmarks.csv}
\ExplSyntaxOn
\RenewDocumentCommand \DTLdisplaydbAddItem 
 { m m m m m m m m } 
{
 \int_compare:nNnTF
  { #7 } = { \c_one_int }
 {
  % insert highlight if average greater than 70
   \fp_compare:nNnT
  { \DTLdatumvalue \AverageScore } > { 70 }
  { 
  \tl_put_right:Nn #1 { \rowcolor {yellow} }
  }
  \DTLaction[ return={\l_tmpa_tl=Forename} ]
  { current ~ row ~ values }
  \datatool_if_null_or_empty:NTF \l_tmpa_tl
  {
  \tl_put_right:Nn #1 { #3 { #2 } }
   }
  {
   \tl_put_right:Nx #1 
    { \exp_not:N #3 { \exp_not:n { #2 }, ~ \exp_not:V \l_tmpa_tl } }
  }
  }
 {
  \tl_put_right:Nn #1 { #3 { #2 } }
 }
}
\ExplSyntaxOff 

\newcommand{\rowfilter}[3]{% 
 \DTLaction[
  options={mean},datum={round=1},
  keys={Assign1-},
  return={\AverageScore=mean}
  ]{current row aggregate}% calculate average
 \DTLifnumlt{\AverageScore}{50}% 
 {}% skip if average less than 50
 {#3}% include this row otherwise
} 

\newcommand{\appendaverage}[2]{% 
 \appto#1{&}% 
 \eappto#1{\expandonce\AverageScore}% 
} 
\begin{document}
\DTLaction[
 options={
  only-keys={Surname,StudentNo},
  align-specs={lrr},
  post-row-function={\appendaverage},
  row-condition-function={\rowfilter},
  header-row={Name & Reg.\ No. & Average}
  }
 ]{display} 
\end{document}
