SQL - 将平均列添加到详细信息 table
SQL - Adding an avg column to a detail table
我在使用 Teradata。我有一个订单 table 如下所示。
custID | orderID | month | order_amount
-----------------------------------------
1 | 1 | jan | 10
1 | 2 | jan | 20
1 | 3 | feb | 5
1 | 4 | feb | 7
2 | 5 | mar | 20
2 | 6 | apr | 30
我想在上面的 table 中添加一个名为 "Avg order amount per month per customer" 的列。由于 table 是订单级别,添加此列会导致像下面这样的重复,这是可以的。
custID | orderID | month | order_amount | avgOrdAmtperMonth
-------------------------------------------------------------
1 | 1 | jan | 10 | 15
1 | 2 | jan | 20 | 15
1 | 3 | feb | 5 | 6
1 | 4 | feb | 7 | 6
2 | 5 | mar | 20 | 20
2 | 6 | apr | 30 | 30
我希望输出包含上面的所有列,而不仅仅是 custid 和新列。我不确定如何写这个,因为 table 的一部分是订单级别的,新列需要按客户+月份分组。我该怎么做?
这是一个简单的组平均值:
AVG(order_amount) OVER (PARTITION BY custID, month)
为什么不在查询 table 时进行计算?
select t.*,
avg(order_amount) over (partition by custId, month) as avgOrderAmtPerMonth
from t;
如果您想让它可用于多个下游查询,您可以将其添加到视图中。
实际上将列添加到 table 是维护 "nightmare"。您必须向 table 添加触发器并更新更新、插入和删除的值。
我在使用 Teradata。我有一个订单 table 如下所示。
custID | orderID | month | order_amount
-----------------------------------------
1 | 1 | jan | 10
1 | 2 | jan | 20
1 | 3 | feb | 5
1 | 4 | feb | 7
2 | 5 | mar | 20
2 | 6 | apr | 30
我想在上面的 table 中添加一个名为 "Avg order amount per month per customer" 的列。由于 table 是订单级别,添加此列会导致像下面这样的重复,这是可以的。
custID | orderID | month | order_amount | avgOrdAmtperMonth
-------------------------------------------------------------
1 | 1 | jan | 10 | 15
1 | 2 | jan | 20 | 15
1 | 3 | feb | 5 | 6
1 | 4 | feb | 7 | 6
2 | 5 | mar | 20 | 20
2 | 6 | apr | 30 | 30
我希望输出包含上面的所有列,而不仅仅是 custid 和新列。我不确定如何写这个,因为 table 的一部分是订单级别的,新列需要按客户+月份分组。我该怎么做?
这是一个简单的组平均值:
AVG(order_amount) OVER (PARTITION BY custID, month)
为什么不在查询 table 时进行计算?
select t.*,
avg(order_amount) over (partition by custId, month) as avgOrderAmtPerMonth
from t;
如果您想让它可用于多个下游查询,您可以将其添加到视图中。
实际上将列添加到 table 是维护 "nightmare"。您必须向 table 添加触发器并更新更新、插入和删除的值。