从销售数据计算前两个执行产品类别

时间:2018-04-24 18:58:32

标签: sql google-bigquery

我正在尝试为每位客户构建前2个执行产品类别的KPI。 我有以下相关专栏的销售数据 - customerid,product,product_category,order_qty,product_amt,order_date

我在BQ中使用遗留SQL语法。

1 个答案:

答案 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