获取数据工具数据库中符合条件的特定列的所有值

获取数据工具数据库中符合条件的特定列的所有值

我怎样才能获得与另一列中的特定值匹配的所有名称(例如,所有年龄为 20 的名称都是 Adam、Dora、Franz)?

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

答案1

您可以执行以下操作:

\documentclass{article}
\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}

\newcommand{\gettallnamesofage}[1]{%
    \def\allnamesofage{}%
    \DTLforeach*[\DTLiseq{\Age}{#1}]{data}{\Name=Name, \Age=Age}{%
        \ifdefempty{\allnamesofage}{%
            \let\allnamesofage\Name % first element of list
        }{% append to list
            \eappto\allnamesofage{, \Name}%
        }%
    }%
    All names with age #1 are \allnamesofage.%
}

\begin{document}

\gettallnamesofage{20}

\end{document}

输出:

在此处输入图片描述

答案2

这使用readarray(和listofitems) 而不是datatool

\begin{filecontents*}[overwrite]{data.dat}
Name,Town,Age
Adam,Xcity,20
Berta,Ytown,30
Cesar,Ztington,40
Dora,Ztington,20
Emil,Ytown,30
Franz,Ytown,20
\end{filecontents*}
\documentclass{article}
\usepackage{readarray}
\begin{document}
\def\matchvalue{20}% VALUE TO MATCH
\def\matchcol{3}% COLUMN TO CHECK FOR \matchvalue
\def\resultcol{1}% DESIRED OUTPUT, IF MATCH
\readarraysepchar{\\}
\readdef{data.dat}\mydata
\setsepchar{\\/,}
\ignoreemptyitems
\readlist*\myarray{\mydata}
\foreachitem\z\in\myarray[]{%
  \itemtomacro\myarray[\zcnt,\matchcol]\testvalue
  \ifx\testvalue\matchvalue
    \myarray[\zcnt,\resultcol] \fi
}
\end{document}

在此处输入图片描述

相关内容