2017-03-10 50 views
0

在我的查詢中,我逐行選擇結束餘額。這是消耗100%的CPU,而執行在SQL Server 2014 這裏是我的查詢:SQL選擇命令在執行時消耗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(SUM(l.credit-l.debit) ,0) FROM member_transaction l WHERE l.entry_date<a.entry_date AND [email protected] 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 [email protected] 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 

是否有任何其他的方法來計算,每筆交易按行期末餘額行?請幫我解決這個問題。

這裏是表結構:

CREATE TABLE [member_transaction](
    [id] [int] IDENTITY(1,1) NOT NULL, 
    [member_id] [int] NULL, 
    [t_type] [varchar](50) NULL, 
    [debit] [decimal](12, 2) NOT NULL, 
    [credit] [decimal](12, 2) NOT NULL, 
    [particular] [varchar](100) NULL, 
    [remarks] [varchar](150) NULL, 
    [reference_id] [varchar](50) NULL, 
    [entry_date] [datetime] NOT NULL, 
    [is_succeed] [bit] NOT NULL 
) 

CREATE TABLE [recharge_request](
    [id] [bigint] IDENTITY(1,1) NOT NULL, 
    [mobile_no] [varchar](50) NULL, 
    [amount] [decimal](12, 0) NULL, 
    [user_reference_id] [varchar](50) NULL, 
    [uid] [int] NULL, 
    [rdate] [datetime] NOT NULL, 
    [status] [varchar](50) NOT NULL 
) 
+0

你的實際問題是什麼?您需要知道SQL Server對所有可獲得的資源都很貪婪。 –

+0

@AmitMishra,您正在使用哪個版本的SQL Server?還請張貼表格結構,樣本數據和預期結果。您應該能夠再次加入同一張表,以匹配先前記錄來計算明智的行結算餘額。這[後](http://stackoverflow.com/questions/11310877/calculate-running-total-running-balance)可能會幫助你。 – Venu

+0

簡短的回答是壞的或沒有索引 – gbn

回答

1

假設您在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 
    [email protected] 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') 

如果你想獲取多個成員,那麼你應該在總和的一部分中劃分。

+0

Thnaks @詹姆斯! –