创建SQL查询以汇总一些数据。它很慢,所以我想我会请求一些帮助。
表是一个包含以下内容的日志表:
loc, tag, entrytime, exittime, visits, entrywt, exitwt
我的测试日志中有700,000条记录。 entrytime
和exittime
是时代价值。
我知道我的查询效率很低,因为它在表格中翻了4次。
select
loc, edate, tag,
(select COUNT(*) from mylog as ml
where mvlog.loc = ml.loc
and mvlog.edate = CONVERT(date, DATEADD(ss, ml.entrytime, '19700101'))
and mvlog.tag = ml.tag) as visits,
(select SUM(entrywt - exitwt) from mylog as ml2
where mvlog.loc = ml2.loc
and mvlog.edate = CONVERT(date, DATEADD(ss, ml2.entrytime, '19700101'))
and mvlog.tag = ml2.tag) as consumed,
(select SUM(exittime - entrytime) from mylog as ml3
where mvlog.loc = ml3.loc
and mvlog.edate = CONVERT(date, DATEADD(ss, ml3.entrytime, '19700101'))
and mvlog.tag = ml3.tag) as occupancy
from
eventlogV as mvlog with (INDEX(pt_index))
索引pt_index
由列tag
和loc
组成。
当我运行此查询时,它在大约30秒内完成。由于我的查询效率低下,我相信它会更好。
任何想法都赞赏。
答案 0 :(得分:2)
好像你可以将mOLLog LEFT JOIN加入eventlogV一次并得到相同的结果。
SELECT mvlog.loc,
mvlog.edate,
mvlog.tag,
COUNT(ml.loc) AS visits,
SUM(entrywt - exitwt) AS consumed,
SUM(exittime - entrytime) AS occupancy
FROM eventlogV AS mvlog
LEFT OUTER JOIN mylog ml ON mvlog.loc = ml.loc
AND mvlog.edate = CONVERT(DATE,DATEADD(ss,ml.entrytime,'19700101'))
AND mvlog.tag = ml.tag
GROUP BY mvlog.loc,
mvlog.edate,
mvlog.tag