SQL select命令在执行时消耗100%的CPU
在我的查询中,我选择逐行期末余额。它在执行is sql server 2014时消耗100%的CPU。 我的问题是:SQL select命令在执行时消耗100%的CPU,sql,sql-server,Sql,Sql Server,在我的查询中,我选择逐行期末余额。它在执行is sql server 2014时消耗100%的CPU。 我的问题是: ;WITH summary(id,reference_id,entry_date,particular,remarks,debit,credit,balance)AS( SELECT id, reference_id, entry_date, particular, remarks, debit, credit, (credit-debit)+(SELECT ISNULL(SU
;WITH summary(id,reference_id,entry_date,particular,remarks,debit,credit,balance)AS(
SELECT
id,
reference_id,
entry_date,
particular,
remarks,
debit,
credit,
(credit-debit)+(SELECT ISNULL(SUM(l.credit-l.debit) ,0) FROM member_transaction l WHERE l.entry_date<a.entry_date AND l.member_id=@mId AND is_succeed=1 AND isnull(l.reference_id,0) NOT IN(SELECT user_reference_id FROM recharge_request WHERE status='Failure'))AS balance
FROM member_transaction a
WHERE member_id=@mId AND is_succeed=1
AND isnull(reference_id,0) NOT IN(SELECT user_reference_id FROM recharge_request WHERE status='Failure')),
openingbalance(
id,
reference_id,
entry_date,
particular,
remarks,
debit,
credit,
balance
)AS(SELECT TOP 1 0,'','','OPENING BALANCE','',0,0,balance FROM summary WHERE entry_date<'2017/03/10' ORDER BY entry_date DESC
)SELECT * FROM openingbalance UNION SELECT * FROM summary ORDER BY entry_date DESC
假设您使用的是SQL Server 2012+,您应该尝试以下操作:
SELECT
id,
reference_id,
entry_date,
particular,
remarks,
debit,
credit,
sum(isnull(credit,0)-isnull(debit,0)) over (order by entry_date asc) AS balance
FROM
member_transaction a
WHERE
member_id=@mId AND
is_succeed=1 AND
not exist (select 1 FROM recharge_request r WHERE r.user_reference_id = a.reference_id and r.status='Failure')
如果您想获取多个成员,那么应该在总和的over部分使用partition by。您的实际问题是什么?您需要知道SQL Server对它所能获得的所有资源都很贪婪。@AmitMishra,您使用的是哪个版本的SQL Server?请同时发布表格结构、样本数据和预期结果。您应该能够再次联接同一个表,以匹配计算行期末余额的上一条记录。这可能会对你有所帮助。简短的回答是“不好”或“不”indexes@AmitMishra,也请添加样本数据。请参考@Venu,其大量数据。如果用10条或50条记录执行,效果很好。Thnaks@James!
SELECT
id,
reference_id,
entry_date,
particular,
remarks,
debit,
credit,
sum(isnull(credit,0)-isnull(debit,0)) over (order by entry_date asc) AS balance
FROM
member_transaction a
WHERE
member_id=@mId AND
is_succeed=1 AND
not exist (select 1 FROM recharge_request r WHERE r.user_reference_id = a.reference_id and r.status='Failure')