某互联网公司数据分析岗位SQL面试题,要求计算每个卖家销量最高的商品。
-- 商家卖货记录表
CREATE TABLE t5 (seller_id int, buyer_id int, item_id int, num int);
INSERT INTO t5 VALUES (1, 11, 1, 100), (1, 12, 1, 200), (1, 12, 2, 300);
INSERT INTO t5 VALUES (2, 11, 1, 100), (2, 12, 3, 200);
-- 计算每个卖家销量最高的商品
SELECT seller_id,item_id,total FROM (
SELECT seller_id,item_id,SUM(num) AS total,RANK() over(PARTITION BY seller_id ORDER BY SUM(num) DESC) AS rk FROM t5 GROUP BY seller_id,item_id) s where s.rk=1;
某互联网公司数据分析岗位SQL面试题,要求计算每个商家的自建商品销量占总销量的比例。
-- 商家卖货记录表
CREATE TABLE t4 (seller_id integer, buyer_id integer, item_id integer, order_cnt integer, price numeric, source_type tinyint);
INSERT INTO t4 VALUES (1, 11, 1, 5, 9.9, 1), (1, 12, 2, 15, 16.9, 0);
INSERT INTO t4 VALUES (2, 13, 3, 10, 89.9, 0), (2, 14, 4, 11, 1999, 0);
-- 商家自建商品销售量占比
SELECT seller_id, SUM(CASE source_type WHEN 1 THEN order_cnt ELSE 0 END)/SUM(order_cnt) AS ratio FROM t4 GROUP BY seller_id;