Talend 聚合行

Talend 聚合行或 tAggregateRow 组件用于根据给定的分组列对数值列数据执行聚合,并返回结果。我们可以使用此聚合行组件来查找按区域划分的销售总额、按州划分的订单总数等。

在此 Talend 聚合行示例中,我们使用了 SQL Server 数据库的 Customer 表。下面的屏幕截图显示了该表中的数据。

Customer Sales Table with HireDate

Talend 聚合行示例

首先,拖放 DBConnection、DBInput 和 DBCommit 以建立 SQL Server 连接。接下来,我们从元数据中选择了 Customers 表。

Configure Server Connection and write table Select query

接下来,将 Talend tAggregateRow 组件从面板拖到作业设计中。从下面的工具提示中可以看到,tAggregateRow 匹配 SQL GroupBy 功能。它接收数据流并根据 Group By 列进行聚合。

Talend Aggregate Row 3

请将 DBInput 主行连接到 tAggregateRow。通常,输入列不会与 tAggregateRow 同步。因此,请点击“编辑 Schema”按钮为 tAggregateRow 添加必需的列。

请记住,您只需要添加 Group By 列和聚合列。因为所有未参与聚合的列都必须放在 Group By 部分。在这里,我们添加了 Occupation、Yearly Income 和 Sales 列。

在 Talend tAggregateRow 组件的“组件”选项卡中,有一个“Group By”部分和一个“Operations”部分。在“Group By”部分,您需要选择 Group By 列并进行映射。

  • 输出列:请选择分组的输出列。它是 tAggregateRow 输出模式中的同一列。
  • 输入列位置:在这里,您需要从源(即 tDBInput)映射或选择输入列。

请使用“添加”(加号)按钮添加 Group By 列。在这里,我们添加了 Occupation 列,并将其与输入列进行了映射。您可以使用下拉列表查看其他列。

Talend Aggregate Row 6

在 Talend 聚合行“操作”部分,我们有

  • 输出列:请选择聚合的输出列。它是 tAggregateRow 输出模式中的一列。
  • 函数:请选择您要执行的聚合。例如,Sum、Avg 等。
  • 输入列位置:在这里,您需要从源(即 tDBInput)映射或选择输入列。
  • 忽略空值:您要忽略空值吗?

默认情况下,当您单击加号按钮时,Talend 将添加 tAggregateRow 输出模式中的第一个数值列,并选择 count 函数。

Talend Aggregate Row 8

以下屏幕截图显示了 Talend 中可用的聚合函数列表。我已在 SQL 教程中对其进行了说明,请参考相同的教程。

List of available functions in Talend Aggregate Row

如您所见,我们正在按职业对客户进行分组,并查找年度收入的总和以及平均销售额。

Talend Aggregate Row 10

完成 tAggregateRow 配置后,我们将使用 DBOutput 将聚合行输出保存在 SQL 数据库中。在这里,我们将 Talend_tAggregateRow 表创建为目标表。

让我们运行 Talend 聚合行作业。

Run the Talend Aggregate Row Job

我将打开 Management studio 来检查 tAggregateRow 的结果。为了清楚起见,我们使用了 Customers 表上的 T-SQL 查询来将结果与 tAggregateRow 进行比较。

SELECT [Occupation]
,SUM([YearlyIncome]) AS [YearlyIncome]
,AVG([Sales]) AS [Sales]
FROM [SQL Tutorial].[dbo].[Customer]
GROUP BY [Occupation]
ORDER BY YearlyIncome DESC
Check the Result

这次,我们使用了 Education 字段,因此也在 Talend 聚合行模式中添加了它们。

接下来,我们在 Group By 中使用了 Education 列。这意味着,首先,客户将按 Education 分组,然后按职业分组,并执行 Sum 和 Average。

Talend Aggregate Row 16

请检查 Talend 聚合行结果。

Check the Result of Multiple Group by columns

我们使用的代码是

SELECT Education, [Occupation] ,SUM([YearlyIncome]) AS [YearlyIncome]
,AVG([Sales]) AS [Sales]
FROM [SQL Tutorial].[dbo].[Customer]
GROUP BY Education, [Occupation] ORDER BY YearlyIncome DESC

我将只选择 Occupation 列,然后创建几个新的列来存储输出。

Talend Aggregate Row with multiple grouping columns

接下来,我们将 Talend 的大多数聚合函数用作输出。

Talend Aggregate Row 19

Talend 聚合行作业的结果

Result table

代码是

SELECT [Occupation]
,SUM([YearlyIncome]) AS [IncomeSum]
,AVG([YearlyIncome]) AS [IncomeAvg]
,COUNT([YearlyIncome]) AS [IncomeCount]
,MIN([YearlyIncome]) AS [IncomeMin]
,MAX([YearlyIncome]) AS [IncomeMax]
,STDEV([YearlyIncome]) AS [IncomeStd]
FROM [SQL Tutorial].[dbo].[Customer]
GROUP BY [Occupation] ORDER BY IncomeSum DESC;