无论如何,我可以优化此查询吗?目前运行下面的查询需要半个小时。
我已将其作为子查询尝试并尝试添加Outer Apply
,但我发现性能没有任何改善。我将如何改善这种表现?
以下是查询:
SELECT invoiceno,
dealno,
customerno,
vendorno,
previous1 = (SELECT TOP 1 CASE @Tax
WHEN 0 THEN ( i1.invoicetotal - i1.invoicetax )
ELSE i1.invoicetotal
END
FROM invoiceview i1 WITH (NOLOCK)
WHERE --ii1.orderid=
i1.orderid = do.orderid
AND i1.invoiceno != i.invoiceno
AND i1.billingend < i.billingend
AND i1.status NOT IN ( 'ESTIMATE', 'VOID' )
ORDER BY i1.billingend DESC),
previousstatus1 =(SELECT TOP 1 Rtrim(i1.status)
FROM invoiceview i1 WITH (NOLOCK)
--join invoiceitem ii1 with (nolock) on i1.invoiceid = ii1.invoiceid
WHERE --ii1.orderid=
i1.orderid = do.orderid
AND i1.invoiceno != i.invoiceno
AND i1.billingend < i.billingend
AND i1.status NOT IN ( 'ESTIMATE', 'VOID' )
ORDER BY i1.billingend DESC)
FROM invoiceview iv
LEFT OUTER JOIN dealorder do
ON iv.orderid = do.orderid
LEFT OUTER JOIN invoice i
ON iv.invoiceid = i.invoiceid
LEFT OUTER JOIN deal d
ON d.dealid = do.dealid
/*OUTER APPLY ( SELECT TOP 1 RTRIM(i1.status) as previousstatus1, (CASE @Tax WHEN 0 THEN (i1.invoicetotal - i1.invoicetax) ELSE i1.invoicetotal END) as previous1
FROM invoiceview i1 with (nolock)
WHERE i1.orderid = do.orderid and i1.invoiceno ! = i.invoiceno and i1.billingend ) as a */
任何帮助都会非常感激。如果没有以前的状态,则previousstatus1查询最多只能在10秒内执行。
答案 0 :(得分:0)
感谢所有帮助人员。我弄清楚了这个问题。这是视图。一旦我加入了底层表并实际上做了一个外连接而不是子查询,我注意到了一个很大的区别。