从 SQL window 函数中排除分区?
Exclude a partition from a SQL window function?
我的目标是计算不包括当前分区的平均值。在下面的 table 中,我想知道如何生成 avg_prod_rev_oth_cust
列:其他客户的平均产品收入。这可以用 window 函数来完成吗?
cust prod rev avg_prod_rev avg_prod_rev_oth_cust
a x 1 3.5 4.5
a x 2 3.5 4.5
b x 3 3.5 3.5
b x 4 3.5 3.5
c x 5 3.5 2.5
c x 6 3.5 2.5
a y 7 9.5 10.5
a y 8 9.5 10.5
b y 9 9.5 9.5
b y 10 9.5 9.5
c y 11 9.5 8.5
c y 12 9.5 8.5
我正在使用 MariaDB 列存储。我相信 Columnstore 的 window 函数在语法上类似于 Amazon Redshift。
avg_prod_rev_oth_cust
应计算为 "the sum of this product's revenue excluding this customer / divided by the number of sales from other customers"。对于第一次出现: (3+4+5+6)/4 。
您可以使用 self join
和 avg
window 函数执行此操作。
select distinct t1.*,avg(t2.rev) over(partition by t1.prod,t1.rev) as avg_prod_rev_oth_cust
from tbl t1
join tbl t2 on t1.prod=t2.prod
where t1.cust<>t2.cust
没有 window 功能(所以,没有真正回答问题):
SELECT cus,
AVG(rev) AS AvgAll,
( SELECT AVG(rev) AS AvgOther
FROM ws_test
WHERE cus != t1.cus
) AS AvgOther
FROM ws_test AS t1
GROUP BY cus;
我的目标是计算不包括当前分区的平均值。在下面的 table 中,我想知道如何生成 avg_prod_rev_oth_cust
列:其他客户的平均产品收入。这可以用 window 函数来完成吗?
cust prod rev avg_prod_rev avg_prod_rev_oth_cust
a x 1 3.5 4.5
a x 2 3.5 4.5
b x 3 3.5 3.5
b x 4 3.5 3.5
c x 5 3.5 2.5
c x 6 3.5 2.5
a y 7 9.5 10.5
a y 8 9.5 10.5
b y 9 9.5 9.5
b y 10 9.5 9.5
c y 11 9.5 8.5
c y 12 9.5 8.5
我正在使用 MariaDB 列存储。我相信 Columnstore 的 window 函数在语法上类似于 Amazon Redshift。
avg_prod_rev_oth_cust
应计算为 "the sum of this product's revenue excluding this customer / divided by the number of sales from other customers"。对于第一次出现: (3+4+5+6)/4 。
您可以使用 self join
和 avg
window 函数执行此操作。
select distinct t1.*,avg(t2.rev) over(partition by t1.prod,t1.rev) as avg_prod_rev_oth_cust
from tbl t1
join tbl t2 on t1.prod=t2.prod
where t1.cust<>t2.cust
没有 window 功能(所以,没有真正回答问题):
SELECT cus,
AVG(rev) AS AvgAll,
( SELECT AVG(rev) AS AvgOther
FROM ws_test
WHERE cus != t1.cus
) AS AvgOther
FROM ws_test AS t1
GROUP BY cus;