如何获取datatool
数据库中特定列的所有不同值?示例是将下表读入datatool
数据库:
Name,Town,Age
Adam,Xcity,20
Berta,Ytown,30
Cesar,Ztington,40
Dora,Ztington,20
Emil,Ytown,30
Franz,Ytown,20
现在我想获取Xcity, Ytown,Ztington
该数据库中所有城镇()的列表以及该数据库中所有年龄(20,30,40
)的列表(无重复),我可以将其存储在宏/任何内容中,以便以后使用datatool
或重复使用pgffor
。
答案1
datatool
有一个名为的宏\DTLifinlist
,可以检查元素是否在给定的逗号分隔列表中,因此可以在构建所有城镇或年龄的列表时使用它,如下所示:
\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}
结果: