Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SqlServer 开窗函数实例 #34

Open
topcss opened this issue Jul 24, 2019 · 0 comments
Open

SqlServer 开窗函数实例 #34

topcss opened this issue Jul 24, 2019 · 0 comments
Labels

Comments

@topcss
Copy link
Owner

topcss commented Jul 24, 2019

目标:我要统计项目工作量。
梳理:项目有多个钻孔,钻孔有多个回次。先找到每个钻孔的回次最大深度,再求和。
解题:

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
@topcss topcss added the 📀SQL label Jul 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant