我正在尝试为每位客户构建前2个执行产品类别的KPI。 我有以下相关专栏的销售数据 - customerid,product,product_category,order_qty,product_amt,order_date
我在BQ中使用遗留SQL语法。
答案 0 :(得分:4)
这是一种可能的解决方案......
SELECT
customer_id,
product_category,
order_qty
FROM (
SELECT
customerid,
product_category,
SUM(order_qty) AS order_qty,
ROW_NUMBER() OVER(PARTITION BY customerid ORDER BY order_qty DESC) AS rn
FROM
[project:dataset.table]
GROUP BY
1, 2
)
WHERE
rn <= 2
ORDER BY
1, 3 DESC