首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sql聚合函数优化

sql聚合函数优化
EN

Stack Overflow用户
提问于 2017-07-22 03:32:37
回答 1查看 37关注 0票数 0

我正在试图找到一种优化查询的方法,我相信这会占用我的sql查询的巨大time.This:

代码语言:javascript
复制
select
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @sunday), 0),
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @monday), 0),
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and  (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @tuesday), 0),
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @wednesday), 0),
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @thursday), 0),
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @friday), 0),
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountsqlID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @saturday), 0).

我认为查询的每一列都在执行相同的逻辑,除了在日期上的更改作为最后一个约束。有没有办法我可以先计算整个逻辑,比如将结果刷新到临时表中,然后用date作为where子句进行查询。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-22 03:37:10

使用条件聚合:

代码语言:javascript
复制
select sum(case when s.Date = @sunday then s.durationp else 0 end) as sunday,
       sum(case when s.Date = @monday then s.durationp else 0 end) as monday,
       . . .
from Schedule s 
where AccountID = @AccountID and ClientID = @clientidvalue and
      status = 2 and
      (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID));

注意:假设至少有一行符合WHERE条件,我省略了NULL转换。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45245422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档