You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQL窗口函数中优雅统计type='sale'的行数?(替代CTE/子查询方案)

解决方案:用条件聚合实现精准统计

当然有更优雅的实现方式!你不需要依赖CTE或子查询,直接在窗口函数里用条件聚合就能实现只统计type='sale'的行数。

具体修改思路

把原来的count(*) over (partition by order_num, item_id)替换成sum(case when type = 'sale' then 1 else 0 end) over (partition by order_num, item_id)。这个逻辑很直观:

  • 当type等于sale时,返回1,否则返回0
  • 对这个结果求和,就得到了分区内type='sale'的总行数,正好满足你需要QTY返回2的需求

修改后的完整SQL

select 
    order_num, 
    item_id, 
    type, 
    sum(amount) over (partition by order_num, item_id) as total_amount, 
    sum(tax) over (partition by order_num, item_id) as tax, 
    sum(case when type = 'sale' then 1 else 0 end) over (partition by order_num, item_id) as qty 
from scratch.saqib_ali.temp_table 
qualify row_number() over(partition by order_num order by order_num) = 1;

为什么这更优雅?

  • 逻辑紧凑:直接在原查询的窗口函数中完成条件统计,不需要额外的查询层级
  • 可读性强:通过case语句清晰表达了统计的条件,一眼就能看懂要统计的是哪种类型的行
  • 性能友好:避免了额外的子查询/CTE带来的开销,和原查询的执行效率基本一致

内容的提问来源于stack exchange,提问作者Saqib Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:42:40