Skip to content

展示本月消费情况各产品的占比

关键词

嵌套子查询,成本分析,窗口函数,分支判断

相关函数

case when,sum,row_number

查询语句中首先根据产品名称聚合计算各个产品的总支出,使用窗口函数将产品按照支出金额倒序排列;找出支出最多的六个产品,其他的归为其他。 使用饼图中的环图展示,既能看到总的支出,又可以看到各个产品的占比。

SQL
source :bill |
select
  case
    when rnk > 6
    or pretaxamount <= 0 then '其他'
    else ProductName
  end as ProductName,
  sum(PretaxAmount) as PretaxAmount
from(
    select
      *,
      row_number() over(
        order by
          pretaxamount desc
      ) as rnk
    from(
        select
          ProductName,
          sum(PretaxAmount) as PretaxAmount
        from
          log
        group by
          ProductName
      )
  )
group by
  ProductName
order by
  PretaxAmount desc
limit
  1000

SQL查询结果样例:

样例图片