优化sql计数查询
我对 SQL 还很陌生,所以我想知道我是否以最优化的方式这样做。
SELECT DISTINCT ACCOUNTID, ACCOUNT_NAME
(SELECT COUNT(*)
FROM TICKET
WHERE (ACCOUNTID = OPPORTUNITY.ACCOUNTID)) AS [Number Of Tickets],
(SELECT COUNT(*)
FROM TICKET
WHERE (ACCOUNTID = OPPORTUNITY.ACCOUNTID) AND (STATUSCODE = 1 OR
STATUSCODE = 2 OR
STATUSCODE = 3)) AS [Active Tickets]
from OPPORTUNITY
where AccountID > @LowerBound and AccountID < @UpperBound
我想要做的是获取所有帐户的列表,并显示该帐户有多少票以及有多少票处于活动状态(状态代码为 1、2 或 3)。 select 中的 select 是执行此操作的正确方法吗?还是有办法使用诸如 group by 之类的方法来完成此操作。
我最关心的是速度,只需要 3-5 秒即可提取大约 20 条记录,并且查询可能有 1000 个结果。
我不是 DBA,所以对表模式的任何更改都是不可强制的,但需要向上层管理人员恳求。
这是针对 SQL Server 2000 运行的。
编辑-- 正如所有询问它的答案一样,我检查了它。机会和工单索引均按 accountid 升序排列。
I am still fairly new to SQL so I wanted to know if I am doing this the most optimized way.
SELECT DISTINCT ACCOUNTID, ACCOUNT_NAME
(SELECT COUNT(*)
FROM TICKET
WHERE (ACCOUNTID = OPPORTUNITY.ACCOUNTID)) AS [Number Of Tickets],
(SELECT COUNT(*)
FROM TICKET
WHERE (ACCOUNTID = OPPORTUNITY.ACCOUNTID) AND (STATUSCODE = 1 OR
STATUSCODE = 2 OR
STATUSCODE = 3)) AS [Active Tickets]
from OPPORTUNITY
where AccountID > @LowerBound and AccountID < @UpperBound
What I am trying to do is get a list of all accounts and have it show how many tickets the account has and how many are active (have a status code that is 1, 2, or 3). Is the select inside the select the correct way to do this or is there a way it can be done using something like group by.
My biggest concern is speed, it takes 3-5 seconds to just pull around 20 records and the query could potentially have 1000's of results.
I am not the DBA so any changes to table schema are not imposable but will require some pleading with upper management.
This is being run against SQL Server 2000.
EDIT--
as all of the answers where asking about it I checked on it. Both Opportunity and ticket index on accountid ascending.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为下面的内容在逻辑上应该是等效的并且更有效。显然,你的目的是从这两个方面进行测试!
如果您可以查看执行计划,那么您应该检查两个表中 ACCOUNTID 上是否存在索引并且正在使用。
I think the below should be logically equivalent and more efficient. Obviously test both aspects your end!
IF you can view the execution plans then you should check indexes exist on ACCOUNTID in both tables and are being used.
SQL 引擎(即使在 2000 年)足够智能来优化该 SQL。根据您的性能数据和如此少的结果,我猜测源数据有一堆记录,并且没有 sql 所需的索引。
确保 Opportunity.AccountID 上有索引,Ticket.AccountID 上也有索引。
The SQL engine (even in 2000) is smart enough to optimize that sql. Based on your performance numbers with such few results, I'm guessing the source data had a bunch of records and does not have the indexes the sql needs.
Make sure there is an index on Opportunity.AccountID and an index on Ticket.AccountID.