5

how can I get all different values of a specific column in a datatool database? Example is the following table read into a datatool database:

Name,Town,Age
Adam,Xcity,20
Berta,Ytown,30
Cesar,Ztington,40
Dora,Ztington,20
Emil,Ytown,30
Franz,Ytown,20

Now I'd like to get a list of all towns (Xcity, Ytown,Ztington) in that database and of all ages (20,30,40) in that database without duplicates, that I can store in macro/whatever to reuse later with datatool or pgffor.

5

datatool has a macro called \DTLifinlist which can check if an element is in the given comma-separated list, so this can be used when constructing a list of all the towns or ages, like this:

\documentclass{article}

\usepackage{etoolbox}
\usepackage{datatool}

\begin{filecontents}{test.csv}
Name,Town,Age
Adam,Xcity,20
Berta,Ytown,30
Cesar,Ztington,40
Dora,Ztington,20
Emil,Ytown,30
Franz,Ytown,20
\end{filecontents}

\DTLloaddb{data}{test.csv}

\begin{document}

\newcommand*{\uniquetowns}{}
\newcommand*{\uniqueages}{}

\DTLforeach*{data}{\Town=Town,\Age=Age}{%
  \expandafter\DTLifinlist\expandafter{\Town}{\uniquetowns}%
  {}% do nothing, already in list
  {% add to list
    \ifdefempty{\uniquetowns}%
    {\let\uniquetowns\Town}% first element of list
    {% append to list
      \eappto\uniquetowns{,\Town}%
    }%
  }%
  % Similarly for age
  \expandafter\DTLifinlist\expandafter{\Age}{\uniqueages}%
  {}% do nothing, already in list
  {% add to list
    \ifdefempty{\uniqueages}%
    {\let\uniqueages\Age}% first element of list
    {% append to list
      \eappto\uniqueages{,\Age}%
    }%
  }%
}

List of unique towns: \uniquetowns.

List of unique ages: \uniqueages.
\end{document}

Result:

Resulting image

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.