简体   繁体   中英

Speeding up SQL Server cross apply to get aggregated data

In SQL Server, I am trying to put together a single query which grabs a row and includes the aggregated data from a two hour window before that row as well as aggregated data from one hour window after. How can I make this run faster?

The rows have time stamps to a millisecond precision, and are not evenly spaced. I have over 50 million rows in this table, and the query does not seem to be completing. There are indexes in many places, but they don't seem to help. I was also thinking about using a window function, but I am not sure that its possible to have a sliding window with unevenly distributed rows. Also, for the future one hour window, I am not sure how that would be done with a SQL window.

Box is a string and has 10 unique values. Process is a string and has 30 unique values. The average duration_ms is 200 ms. Errors account for less than 0.1% of the data. The 50 million rows describes a years worth of data.

select 
c1.start_time,
c1.end_time,
c1.box,
c1.process,
datediff(ms,c1.start_time,c1.end_time) as duration_ms,
datepart(dw,c1.start_time) as day_of_week,
datepart(hour,c1.start_time) as hour_of_day,
c3.*,
c5.*
from metrics_table c1
cross apply
(select 
    avg(cast(datediff(ms,c2.start_time,c2.end_time) as numeric)) as avg_ms,
    count(1) as num_process_total,
    count(distinct process) as num_process_unique,
    count(distinct box) as num_box_unique
    from metrics_table c2
    where datediff(minute,c2.start_time,c1.start_time) <= 120
    and c1.start_time> c2.start_time
    and c2.error_code = 0
) c3
cross apply
(select
    avg(case when datediff(ms,c4.start_time,c4.end_time)>1000 then 1.0 else 0.0 end) as percent_over_thresh
    from metrics_table c4
    where datediff(hour,c1.start_time,c4.start_time) <= 1
    and c4.start_time> c1.start_time
    and c4.error_code= 0
) c5
where
c1.error_code= 0

Edit

Version: SQL Azure 12.0

Adding execution plan: 在此输入图像描述

The following should be a step in the right direction... Note: c2.start_time & c4.start_time are no longer wrappen in DATEDIFF functions making them SARGable...

SELECT
    c1.start_time,
    c1.end_time,
    c1.box,
    c1.process,
    DATEDIFF(ms, c1.start_time, c1.end_time) AS duration_ms,
    DATEPART(dw, c1.start_time) AS day_of_week,
    DATEPART(HOUR, c1.start_time) AS hour_of_day,
    --c3.*,
    avg_ms = CASE WHEN 
    c5.*
FROM
    dbo.metrics_table c1
    CROSS APPLY (
                SELECT
                    AVG(CAST(DATEDIFF(ms, c2.start_time, c2.end_time) AS NUMERIC)) AS avg_ms,
                    COUNT(1) AS num_process_total,
                    COUNT(DISTINCT process) AS num_process_unique,
                    COUNT(DISTINCT box) AS num_box_unique
                FROM
                    dbo.metrics_table c2
                WHERE
                    --DATEDIFF(minute,c2.start_time,c1.start_time) <= 120
                    c2.start_time <= DATEADD(MINUTE, -120, c1.start_time)
                    --and c1.start_time> c2.start_time
                    AND c2.error_code = 0
                ) c3
    CROSS APPLY (
                SELECT
                    AVG(CASE WHEN DATEDIFF(ms, c4.start_time, c4.end_time) > 1000 THEN 1.0 ELSE 0.0 END
                    ) AS percent_over_thresh
                FROM
                    dbo.metrics_table c4
                WHERE
                    --DATEDIFF(HOUR, c1.start_time, c4.start_time) <= 1
                    c4.start_time >= DATEADD(HOUR, 1, c1.start_time)
                    --and c4.start_time> c1.start_time
                    AND c4.error_code = 0
                ) c5
WHERE
    c1.error_code = 0;

Of course, making a query SARGable doesn't do any good unless there's an appropriate index available. The following should be good for all 3 metrics_table references... (see what indexes are currently available, there's a chance that you may not need to create a new index)

CREATE NONCLUSTERED INDEX ixf_metricstable_errorcode_starttime ON dbo.metrics_table (
    error_code,
    start_time
    )
INCLUDE (
    end_time,
    box,
    process
    )
WHERE 
    error_code = 0;

I used Between and got good performance in my simple test rig. I've also used columnstore as 50 million records is DW volumes:

CREATE TABLE dbo.metrics_table (
    rowId       INT IDENTITY,
    start_time  DATETIME NOT NULL,
    end_time    DATETIME NOT NULL,
    box         VARCHAR(10) NOT NULL,
    process     VARCHAR(10) NOT NULL,
    error_code  INT NOT NULL
);


-- Add records
;WITH cte AS (
SELECT TOP 3334 ROW_NUMBER() OVER ( ORDER BY ( SELECT 1 ) ) rn
FROM sys.columns c1
    CROSS JOIN sys.columns c2
    CROSS JOIN sys.columns c3
)
INSERT INTO dbo.metrics_table ( start_time, end_time, box, process, error_code )
SELECT
    DATEADD( ms, rn, DATEADD( day, rn % 365, '1 Jan 2017' ) ) AS start_time,
    DATEADD( ms, rn % 409, DATEADD( ms, rn, DATEADD( day, rn % 365, '1 Jan 2017' ) ) ) AS end_time,
    'box' + CAST( boxes.box AS VARCHAR(10) ) box,
    'process' + CAST( boxes.box AS VARCHAR(10) ) process,
    ABS( CAST( rn % 3000 AS BIT ) -1 ) error_code
FROM cte c
    CROSS JOIN ( SELECT TOP 10 rn FROM cte ) AS boxes(box)
    CROSS JOIN ( SELECT TOP 30 rn FROM cte ) AS processes(process);


-- Create normal clustered index to order the data
CREATE CLUSTERED INDEX cci_metrics_table ON dbo.metrics_table ( start_time, end_time, box, process );
--CREATE CLUSTERED INDEX cci_metrics_table ON dbo.metrics_table ( box, process, start_time, end_time );

-- Convert to columnstore
CREATE CLUSTERED COLUMNSTORE INDEX cci_metrics_table ON dbo.metrics_table WITH ( MAXDOP = 1, DROP_EXISTING = ON );



IF OBJECT_ID('tempdb..#tmp1' ) IS NOT NULL DROP TABLE #tmp1

-- two hour window before, 1 hour window after
SELECT
    c1.start_time,
    c1.end_time,
    c1.box,
    c1.process,
    DATEDIFF( ms, c1.start_time, c1.end_time ) AS duration_ms,
    DATEPART( dw, c1.start_time ) AS day_of_week,
    DATEPART( hour, c1.start_time ) AS hour_of_day,
    c2.xavg,
    c2.num_process_total,
    c2.num_process_unique,
    c2.num_box_unique,
    c3.percent_over_thresh

INTO #tmp1

FROM dbo.metrics_table c1
    CROSS APPLY
        (
        SELECT
            COUNT(1) AS num_process_total, 
            AVG( CAST( DATEDIFF( ms, start_time, end_time ) AS NUMERIC ) ) xavg,
            COUNT( DISTINCT process ) num_process_unique,
            COUNT( DISTINCT box ) num_box_unique
        FROM dbo.metrics_table c2
        WHERE c2.error_code = 0
          AND c2.start_time Between DATEADD( minute, -120, c1.start_time ) And c1.start_time
          AND c1.start_time > c2.start_time
        ) c2

    CROSS APPLY
        (
        SELECT
            AVG( CASE WHEN DATEDIFF( ms, c4.start_time, c4.end_time ) > 1000 THEN 1.0 ELSE 0.0 END ) percent_over_thresh
        FROM dbo.metrics_table c4
        WHERE c4.error_code = 0
          AND c4.start_time Between c1.start_time And DATEADD( minute, 60, c1.start_time )
          AND c4.start_time > c1.start_time
        ) c3

WHERE error_code = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM