如何优化此查询,以便从View检索数据

时间:2019-07-19 07:13:12

标签: sql-server

我正在使用以下查询来检索一些数据,但这大约需要1分30秒 获取数据。我可以优化它吗 这里vOrderDetail是一个视图

SELECT VORD.[OrderType] AS [OrderType],SUM(ISNULL(VORD.[Balance],0)) TotalPayment,
SUM(ISNULL(VORD.[PaidPayment],0)) PaymentReceived,SUM(ISNULL(VORD.[Balance],0) - ISNULL(VORD.[PaidPayment],0)) AS PaymentLeft
FROM vOrderDetail VORD
INNER JOIN Orders ORD  ON ORD.Id=VORD.[OrderId]
WHERE ORD.SellerId = 1 AND VORD.[OrderDate]>='2019-05-01 00:00:00.000' AND VORD.[OrderDate]<'2019-06-01 00:00:00.000' 
GROUP BY VORD.[OrderType]

1 个答案:

答案 0 :(得分:0)

尝试这种方式:

SELECT 
    VORD.[OrderType] AS [OrderType], 
    SUM(
        ISNULL(VORD.[Balance], 0)
        ) TotalPayment, 
    SUM(
        ISNULL(VORD.[PaidPayment], 0)
        ) PaymentReceived, 
    SUM(
        ISNULL(VORD.[Balance], 0) - ISNULL(VORD.[PaidPayment], 0)
    ) AS PaymentLeft 
    FROM vOrderDetail VORD 
        WHERE EXISTS
            (
                SELECT
                    1
                    FROM Orders
                        WHERE SellerId = 1
                            AND Id = VORD.[OrderId] 
            )
        AND CAST(VINS.[OrderDate] AS DATE) = CAST('2019-05-01' AS DATE)
        GROUP BY 
            VORD.[OrderType]

由于您没有在任何地方使用联接的任何列,因此我将Join替换为Exists,并用=更改了check间