如何使这个 SQL 查询更高效?下面显示的 CteFinal 代码是我的查询的一部分,我的查询最多需要 6 分钟。cteMonth 如下所示。cteDetail 是另一个直接从数据库中提取信息的 cte,运行时间不到一秒。
CteFinal 所做的是创建缺少的会计期间行,同时包括 f.FiscalPeriod=0 行中的一些列数据。
我不能添加、删除或更改表上的任何索引,因为这是一个 ERP 数据库,我不允许进行这些类型的更改。
CteFinal:
SELECT Account,Month, CONVERT(DATETIME, CAST(@Year as varchar(4)) + '-' + CAST(Month as VARCHAR(2)) + '-' + '01', 102) JEDate
,accountdesc,'' Description,'' JournalCode,NULL JournalNum,NULL JournalLine
,'' LegalNumber,'' CurrencyCode,0.00 DebitAmount,0.00 CreditAmount,fiscalcalendarid,company,bookid,SegValue2,SegValue1,SegValue3,SegValue4
FROM cteDetail f
CROSS JOIN cteMonths m
WHERE f.FiscalPeriod=0 and not exists(select * from cteDetailADDCreatedZero x where x.Account=f.Account and x.FiscalPeriod=Month)
CteMonth:
cteMonths (Month) AS(
select 0 as Month
UNION select 1 as Month
UNION select 2 as Month
UNION select 3 as Month
UNION select 4 as Month
UNION select 5 as Month
UNION select 6 as Month
UNION select 7 as Month
UNION select 8 as Month
UNION select 9 as Month
UNION select 10 as Month
UNION select 11 as Month
UNION select 12 as Month)
谢谢!