0

以下是我的嵌套 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 子句(Select UserID, X.Browser),只需 1 秒即可执行,仅返回 197 行。但是,当我执行整个嵌套查询时,需要将近 6 分钟才能返回结果。谁能帮我理解为什么需要这么长时间?

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

4

2 回答 2

1

这对我有用。我更改了顺序:首先是 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
于 2013-06-13T13:12:36.003 回答
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
于 2013-06-13T11:49:08.057 回答