SqlServer 开窗函数实例
topcss opened this issue · comments
Jack commented
目标:我要统计项目工作量。
梳理:项目有多个钻孔,钻孔有多个回次。先找到每个钻孔的回次最大深度,再求和。
解题:
1.找到各个钻孔最深的记录
select ZKBH,MAX(CAST(JSSD as FLOAT)) as Depth
from ZKHCXX where zkbh in (select zkbh from ZKXX where oaid = 'xxx')
GROUP BY ZKBH
2.求和
select Sum(Depth) from (
select ZKBH,MAX(CAST(JSSD as FLOAT)) as Depth
from ZKHCXX where zkbh in (select zkbh from ZKXX where oaid = 'xxx')
GROUP BY ZKBH
)
3.纳尼!语法错误。显然不能把 group by 包到查询中,说明此路不同。
> [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]')' 附近有语法错误。 (102)
4.开窗函数出马,一个顶俩。
select Sum(depth) from
(
select
row_number() over(partition by ZKBH order by cast(JSSD AS FLOAT) desc) as rn,
CAST(JSSD as FLOAT) as depth
from ZKHCXX where zkbh in (select zkbh from ZKXX where oaid = 'xxx')
) t
where t.rn = 1