登录统计策略T-SQL

时间:2016-09-05 14:06:54

标签: sql-server tsql

我们拥有一个拥有数十万用户的大型网站。我们将登录信息存储在每个登录一行的表中。该表在几个月后存档。

我们希望在此表中显示组织中OrganisationUnits的登录统计信息。用户可以成为几个organisationUnits的一部分。

示例查询:

 SELECT o.name,
     (select count(l.loginID) 
      from logins AS l 
        LEFT JOIN organisationUnitParticipants AS op 
          ON l.userID = op.userID 
      WHERE op.organisationUnitID = o.organisationUnitID 
        AND (logintime BETWEEN @startDate AND @endDate)) AS loginCount
 FROM organisationUnits AS o
 WHERE o.organisationID = @organisationID

如果我将日期设置为月份间隔,则此查询大约需要14秒。索引存在且不进行表扫描。

需要这么长时间的原因只是登录表中的大量数据。

我正在寻找一种更好的方式来存储数据或至少更好的SQL脚本。

用户可以跳进和离开organisationUnits。没有必要保留历史,我们只想在今天的位置计算。

1 个答案:

答案 0 :(得分:0)

试试这个:

select o.name, count(l.loginID) 
from logins AS l 
   left join organisationUnitParticipants op 
       on op.userID = l.userID 
   join organisationUnits o 
       on o.organisationUnitID = op.organisationUnitID 
where o.organisationID = @organisationID
   and logintime BETWEEN @startDate AND @endDate
group by o.name
相关问题