在SQL中对数据进行分区时Agg函数
我有一张这样的桌子:在SQL中对数据进行分区时Agg函数,sql,hive,Sql,Hive,我有一张这样的桌子: store_id industry_id cust_id amount gender 1 100 1000 1.00 M 2 100 1000 2.05 M 3 100 1000 3.15 M 4 100 1000 4.00 M 5
store_id industry_id cust_id amount gender
1 100 1000 1.00 M
2 100 1000 2.05 M
3 100 1000 3.15 M
4 100 1000 4.00 M
5 100 2000 5.00 F
6 200 2000 5.20 F
7 200 5000 6.05 F
8 200 6000 7.10 F
以下是创建此表的代码:
CREATE TABLE t1(
store_id int,
industry_id int,
cust_id int,
amount float,
gender char
);
INSERT INTO t1 VALUES(1,100,1000,1.00, 'M');
INSERT INTO t1 VALUES(2,100,1000,2.05, 'M');
INSERT INTO t1 VALUES(3,100,1000,3.15, 'M');
INSERT INTO t1 VALUES(4,100,1000,4.00, 'M');
INSERT INTO t1 VALUES(5,100,2000,5.00, 'F');
INSERT INTO t1 VALUES(6,200,2000,5.20, 'F');
INSERT INTO t1 VALUES(7,200,5000,6.05, 'F');
INSERT INTO t1 VALUES(8,200,6000,7.10, 'F');
我想回答的问题是:按行业划分的前20%的客户的平均交易额是多少
这将产生以下结果:
store_id. industry_id avg_amt_top_20
1 100 4.80
2 100 4.80
3 100 4.80
4 100 4.80
5 100 4.80
6 200 7.10
7 200 7.10
8 200 7.10
以下是我目前掌握的情况:
SELECT
store_id, industry_id,
avg(CASE WHEN percentile>=0.80 THEN amount ELSE NULL END) OVER(PARTITION BY industry_id) as cust_avg
FROM(
SELECT store_id, industry_id, amount, cume_dist() OVER(
PARTITION BY industry_id
ORDER BY amount desc) AS percentile
FROM t1
) tmp
GROUP BY store_id, industry_id;
此操作在GROUP BY(包含未聚合列“金额”)上失败。最好的方法是什么
按行业划分的前20%客户的平均交易额是多少
基于这个问题,我不明白为什么store\u id
会出现在结果中
如果我理解正确,您需要按客户汇总以获得总数。然后,您可以使用NTILE()
确定前20%的百分比。最后一步是按行业进行聚合:
SELECT industry_id, AVG(total)
FROM (SELECT customer_id, industry_id, SUM(amount) as total,
NTILE(5) OVER (PARTITION BY industry_id ORDER BY SUM(amount) DESC) as tile
FROM t
GROUP BY customer_id, industry_id
) t
WHERE tile = 1
GROUP BY industry_id
我不清楚为什么所问问题的结果中会出现
store\u id
。我将store\u id保留在结果中,因为我需要在其他查询中使用store\u id查找结果。