我的查询执行时间太长,有谁知道如何优化下面的查询?附: 'temp_db'有1'024'912'779行。
以下是查询:
SELECT
CASE
WHEN user_agent LIKE '%Mobile%'
THEN 'Mobile'
ELSE 'Desktop'
END AS DEVICE,
CAST(DATEADD(hour, +8, timestamp_gmt) AS Date) AS HKDate,
DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)) AS HKHour,
pixel_name AS Pixel,
COUNT(id) AS Fires,
COUNT(DISTINCT id) AS Uu
FROM
temp_db
WHERE
CONVERT(date, timestamp_gmt) BETWEEN DATEADD(day, -3, GETDATE())
AND CONVERT(date, GETDATE())
AND advertiser_name LIKE '%TimCompany%'
GROUP BY
CASE
WHEN user_agent LIKE '%Mobile%'
THEN 'Mobile'
ELSE 'Desktop'
END,
CAST(DATEADD(hour, +8, timestamp_gmt) AS Date),
DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)),
pixel_name;
答案 0 :(得分:0)
试试这个:下面的脚本最小化重复的相同函数调用
SELECT DEVICE,
HKDate,
HKHour,
Pixel
COUNT(ID) Fires,
COUNT(DISTINCT ID) Uu
FROM (
SELECT
CASE WHEN user_agent like '%Mobile%' THEN 'Mobile' ELSE 'Desktop' END AS DEVICE,
CAST(DATEADD(hour,+8,timestamp_gmt) AS Date) AS HKDate,
DATEPART(Hour,DATEADD(hour, +8, timestamp_gmt)) AS HKHour,
pixel_name AS Pixel,
ID
FROM temp_db
WHERE CONVERT(date,timestamp_gmt) BETWEEN DATEADD(day,-3,GETDATE()) AND CONVERT(date,GETDATE()) AND
advertiser_name like '%TimCompany%'
)M
GROUP BY DEVICE,HKDATE,HKHOUR,pixel
答案 1 :(得分:0)
where子句中的日期不是sargable。尝试以下:
SELECT
CASE
WHEN user_agent LIKE '%Mobile%'
THEN 'Mobile'
ELSE 'Desktop'
END AS DEVICE,
CAST(DATEADD(hour, +8, timestamp_gmt) AS Date) AS HKDate,
DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)) AS HKHour,
pixel_name AS Pixel,
COUNT(id) AS Fires,
COUNT(DISTINCT id) AS Uu
FROM
temp_db
WHERE
timestamp_gmt >= convert(date, DATEADD(day, -3, GETDATE()))
and timestamp_gmt < convert(date, DATEADD(day, 1, GETDATE()) )
AND advertiser_name LIKE '%TimCompany%'
GROUP BY
CASE
WHEN user_agent LIKE '%Mobile%'
THEN 'Mobile'
ELSE 'Desktop'
END,
CAST(DATEADD(hour, +8, timestamp_gmt) AS Date),
DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)),
pixel_name;