문제

보기를 사용하여 6 평균을 가져 오는 저장된 절차가 있습니다. SQL 데이터베이스는 SQL Server 2000입니다. 쿼리 분석기에서 실행하면 약 9 초가 걸립니다. 더 나은 성능을 얻으려면 어떻게해야합니까? LINQ를 사용하여 행을 반환하고 평균을 그렇게 결정해야합니까? 더 빠를까요?

다음은 내 현재 Sproc의 예입니다.

create procedure [TestAvg]
(
    @CustomerNumber int
)
as

select
(select AVG(OrderTime) from OrderDetails where ProductID = 12 and DateDiff(day, DateFulfilled, GetDate()) <= 7 and CustomerNumber = @CustomerNumber) as P12D7,
(select AVG(OrderTime) from OrderDetails where ProductID = 12 and DateDiff(day, DateFulfilled, GetDate()) <= 30 and CustomerNumber = @CustomerNumber) as P12D30,
(select AVG(OrderTime) from OrderDetails where ProductID = 12 and DateDiff(day, DateFulfilled, GetDate()) <= 90 and CustomerNumber = @CustomerNumber) as P12D90,
(select AVG(OrderTime) from OrderDetails where ProductID = 16 and DateDiff(day, DateFulfilled, GetDate()) <= 7 and CustomerNumber = @CustomerNumber) as P16D7,
(select AVG(OrderTime) from OrderDetails where ProductID = 16 and DateDiff(day, DateFulfilled, GetDate()) <= 30 and CustomerNumber = @CustomerNumber) as P16D30,
(select AVG(OrderTime) from OrderDetails where ProductID = 16 and DateDiff(day, DateFulfilled, GetDate()) <= 90 and CustomerNumber = @CustomerNumber) as P16D90

또한 위에서 언급 한 견해를 명확히하겠습니다. 이것은 SQL Server 2000이므로 하위 쿼리를 사용하므로 인덱스 된보기를 사용할 수 없습니다. 나는 이것이 결합을 사용하도록 다시 작성할 수 있다고 생각합니다. 그러나 마지막으로 쿼리를 가져 와서 결합을 사용하기 위해 다시 작성했을 때 데이터가 누락되었습니다 (하위 쿼리는 전체 행을 생략 할 수없는 널 값을 반환 할 수 있기 때문에).

도움이 되었습니까?

해결책

나는 데이터를 먼저 테이블 var, 아마도 2 개의 테이블 vars, 1의 경우 1, 16 productID의 경우 1을 테이블 var로 얻는 것을 권장합니다. 이 테이블 vars에서 필요에 따라 AVG를 계산 한 다음 sp에서 Tose를 반환하십시오.

DECLARE @OrderDetails12 TABLE(
        DateFulfilled DATETIME,
        OrderTime FLOAT
)

INSERT INTO @OrderDetails12
SELECT  DateFulfilled,
        OrderTime
FROM    OrderDetails
WHERE   ProductID = 12
AND     DateDiff(day, DateFulfilled, GetDate()) <= 90
and CustomerNumber = @CustomerNumber

DECLARE @OrderDetails16 TABLE(
        DateFulfilled DATETIME,
        OrderTime FLOAT
)

INSERT INTO @OrderDetails16
SELECT  DateFulfilled,
        OrderTime
FROM    OrderDetails
WHERE   ProductID = 16
AND     DateDiff(day, DateFulfilled, GetDate()) <= 90
and CustomerNumber = @CustomerNumber

또한 테이블에 올바른 인덱스를 만들면 많은 도움이됩니다.

다른 팁

데이터베이스 서버를 떠나는 데이터의 양은 분리되지 않은 경우 어떻게됩니까? 데이터 크기의 차이는 서버의 계산 시간이 전송 시간과 로컬 계산에 비해 더 중요하다는 것을 안내합니다.

또한 - 그것을보십시오 DATEDIFF 사용 및 변경하기 쉽도록 최적화 할 수 있도록 변경하십시오 (DateFullFilled> = somecalcatedDate1 대신 DateFullFilled> = somecalcatedDate1을 사용해보십시오. DATEDIFF) - 실행 계획을 검토하여 TABLE_SCAN 대신 인덱스 탐색 (최고) 또는 색인 스캔 (양호)을 사용할 수 있는지 확인하십시오.

또한 CustomerNumber, ProduceID, DateFuild에 인덱스가 있는지 확인하십시오.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top