这是我在三月份运行的SQL查询,运行完美但是当我四月运行时它只是运行并运行
但是,如果我避免总计,它再次运作良好。
如果语法错误或者有替代设计,请提供帮助。
;
WITH T as (
SELECT 0 as seq,0 as [Ref No],'' as [Type],0 as [JV NO] ,0 as[MONTH],DATEADD(day,DATEDIFF(day,0,'20140401')-1,0) as [Date],0 as [Chequ No.],DATEADD(day,DATEDIFF(day,0, '20140401')-1,0) as [Due Date],'Transferred' as [Discription],'' as[Payee],
0 as [Debit], -- ANA DÖVÝZ BORÇ
0 as [Credit], -- ANA DÖVÝZ ALACAK
SUM([#msg_S_0103\T]) as [Amount] -- ANA DÖVÝZ TUTAR
,dbo.fn_CariHarEvrTipUzun(cha_evrak_tip) AS [msg_S_0094]
,cha_RECno
,cha_RECid_RECno
From dbo.fn_HamCariFoy ( N'0',2, N'01',1,null,DATEADD(day,DATEDIFF(day,0,'20140401')-1,0),0,'','' )
inner join CARI_HESAP_HAREKETLERI on CARI_HESAP_HAREKETLERI.cha_RECno = [msg_S_0088]
GROUP BY [#msg_S_1712],[msg_S_0112],cha_evrak_tip ,cha_RECno
,cha_RECid_RECno
union all
Select TOP 100 Percent ROW_NUMBER () over (order by cha_tarihi ) as seq,msg_S_0091 as [Ref No],
msg_S_0003 as [Type],[JV NO],[MONTH],msg_S_0089 as [Date],
case ISNUMERIC(#msg_S_0093) when 1 then
CONVERT(int, ISNULL(NULLIF (#msg_S_0093, ''), 0))
else 0
end as [Chequ No.],
msg_S_0098 as [Due Date],#msg_S_0085 as [Discription],[Payee],
sum([msg_S_0101\T]) as 'Debit',sum([msg_S_0102\T]) as 'Credit',
(sum([msg_S_0101\T])- sum([msg_S_0102\T]))AS 'Amount'
,dbo.fn_CariHarEvrTipUzun(cha_evrak_tip) AS [msg_S_0094]
,cha_RECno
,cha_RECid_RECno
from dbo.fn_CariFoy (N'0',2,N'01',1,DATEADD(day,DATEDIFF(day,0, '20140401')-1,0), '20140401', '20140430',0,N'')
inner join CARI_HESAP_HAREKETLERI on CARI_HESAP_HAREKETLERI.cha_RECno = [msg_S_0088]
group by msg_S_0091,msg_S_0003,msg_S_0089,#msg_S_0093,#msg_S_0085,[MONTH],msg_S_0098 ,cha_RECno,cha_tarihi
,cha_RECid_RECno
,[JV NO],[Payee] ,cha_evrak_tip
order by convert(int,#msg_S_0093)
)
**SELECT * ,(SELECT SUM(Amount) from T as b
Where b.seq <= a.seq )as [Remaining Balance] from T a
order by Date**
计算跑步总数的最佳方法是什么?如何优化上述查询?
答案 0 :(得分:0)
我写的是CURSOR
,正如Tanveer Khan建议的那样。
只需将CTE
的结果插入临时表,避免计算Running Total。
;WITH T AS
(
-- Your queries
)
SELECT * INTO #TEMP
FROM T
现在您需要从上面的临时表中选择结果,以查找CURSOR
的运行总计
DECLARE @Seq INT
DECLARE @Amount NUMERIC(20,2)
DECLARE @Previous@Amount NUMERIC(20,2)=0
-- Here you declare which all columns you need to loop in Cursor
DECLARE CUR CURSOR FOR
SELECT Seq,Amount
FROM #TEMP
ORDER BY Seq;
OPEN CUR
-- Loop starts from here and selects each Seq and Amount of each record in each loop
FETCH NEXT FROM CUR
INTO @Seq,@Amount
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE #TEMP SET RUNNINGTOTAL = @Amount + @Previous@Amount
WHERE Seq = @Seq
-- Saves previous row's cumiliative total in variable
SET @Previous@Amount = @Amount + @Previous@Amount
-- Fetches next record and increments the loop
FETCH NEXT FROM CUR
INTO @Seq,@Amount
END
CLOSE CUR;
DEALLOCATE CUR;
现在,Running Total将保存在临时表的列中,您可以使用
从中进行选择SELECT * FROM #TEMP
请随时提出疑问。 祝福。