Sql嵌套查询执行性能

时间:2013-06-13 11:38:38

标签: sql sql-server performance nested-queries

以下是我的嵌套SQL查询:

SELECT M.UserID, SUM(M.Browser)
FROM
(
    SELECT UserID, X.Browser
    FROM
    (
        SELECT UserName, PCMLogEventID, MAX(Browser) AS Browser
        FROM [PCMDBSERVER].[MISTestPCM_Raw].[dbo].[PCM_Log_FilterSwitchData] 
        WHERE [DateTime] BETWEEN '6/12/2013 12:00:00 AM' AND '6/12/2013 11:59:59 PM'
        GROUP BY UserName, PCMLogEventID
    ) X
    INNER JOIN ( 
        SELECT * 
        FROM PCM_Stat_UserRepository 
        WHERE MachineID='All' 
    ) Y
    ON X.UserName = Y.UserName
) M
GROUP BY M.UserID

内部查询的执行时间 - 使用select子句(选择UserID,X.Browser),只需要1秒钟来执行,只返回197行。但是,当我执行整个嵌套查询时,返回结果大约需要6分钟。任何人都可以帮助我理解为什么需要这么长时间?

编辑: 实际上需要PCMLogEventID。因为PCM_Log_FilterSwitchData中的数据是这样的: 用户名| PCMLogEventID |浏览器 abc | 111 | 0.9 abc | 111 | 1.2 abc | 222 | 1.2 abc | 222 | 3.5 。 。 因此,我首先通过分组UserName&来获取MAX。 PCMLogEventID,然后是它的SUM。

2 个答案:

答案 0 :(得分:1)

这对我有用。我更改了顺序:First MAX,然后是SUM,然后是JOIN。

    Select Y.UserID, P.Browser
    FROM
    (
        SELECT DISTINCT X.UserName, SUM(X.Browser) as Browser
        FROM
        (
            SELECT UserName, PCMLogEventID, MAX(Browser) AS Browser
            FROM [PCMDBSERVER].[MISTestPCM_Raw].[dbo].[PCM_Log_FilterSwitchData] 
            WHERE [DateTime] BETWEEN '6/12/2013 12:00:00 AM' AND '6/12/2013 11:59:59 PM'
            GROUP BY UserName, PCMLogEventID
        ) X
        GROUP BY X.UserName
        ) P
        INNER JOIN
        ( SELECT * FROM PCM_Stat_UserRepository WHERE MachineID='All' ) Y
    ON P.UserName = Y.UserName

答案 1 :(得分:0)

这可能对你有所帮助 -

SELECT M.UserID, Browser = SUM(X.Browser)
FROM
(
    SELECT 
          UserName
        , Browser = MAX(Browser) 
    FROM [PCMDBSERVER].[MISTestPCM_Raw].[dbo].[PCM_Log_FilterSwitchData] 
    WHERE [DateTime] BETWEEN '20130613 12:00:00' AND '20130613 23:59:59'
    GROUP BY UserName
) X
JOIN (
    SELECT 
          UserName
        , UserID 
    FROM dbo.PCM_Stat_UserRepository 
    WHERE MachineID = 'All' 
) M ON X.UserName = Y.UserName
GROUP BY M.UserID