如何显示每个部门每天访问系统的员工数量?

时间:2012-11-21 08:03:57

标签: sql sql-server-2008-r2

我是使用C#的ASP.NET新开发人员。我为其中一家公司开发了一个基于Web的应用程序,现在我需要开发一个日志,显示访问系统的唯一人数。例如,AA部门的员工A和B今天访问了系统。员工A在同一天访问了系统两次。日志应该显示,AA部门有两名员工今天访问了系统而不是三名。

我有以下数据库设计:

Employee Table: Username, Name, DivisionCode (DivisionCode is a foreign key to SapCode)
Divisions Table: SapCode DivisionShortcut   
Log Table: ID, Username, DateTimeAccessing

我编写了以下查询,显示用户名,员工姓名,部门和DateTimeAccessing:

SELECT     dbo.[Log].Username, dbo.employee.Name, dbo.Divisions.DivisionShortcut, dbo.[Log].DateTimeAccessing
FROM         dbo.employee INNER JOIN
                      dbo.[Log] ON dbo.employee.Username = dbo.[Log].Username INNER JOIN
                      dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode

查询应显示每天根据部门和日期访问系统的员工数量,例如:

At Nove 21, Division AA = 2    
   Nove 21, Division BB = 7    
   Nove 20, Division AA = 12 and so on

那怎么做?

*的 更新: * 我现在使用以下查询:

SELECT     CONVERT(varchar(10), l.DateTimeAccessing, 120) AS Date, d.DivisionShortcut, COUNT(DISTINCT l.Username) AS Cnt
FROM         dbo.employee AS e INNER JOIN
                      dbo.[Log] AS l ON e.Username = l.Username RIGHT OUTER JOIN
                      dbo.Divisions AS d ON e.DivisionCode = d.SapCode
GROUP BY CONVERT(varchar(10), l.DateTimeAccessing, 120), d.DivisionShortcut

现在的问题是,例如,如果我想查看所有部门的今天或11月10日的统计数据,则日期列将显示该部门的NULL值,该部门在该日期没有员工访问系统。 为什么?以及如何解决它?

2 个答案:

答案 0 :(得分:1)

使用count(distinct)来计算用户数量,并使用group by将结果分组为除数和日期。

您可以使用convert将日期作为日期时间的字符串获取,但要注意它会稍微减慢查询速度。

select d.DivisionShortcut, convert(varchar(10),l.DateTimeAccessing,120), count(distinct l.Username) as Cnt
from dbo.employee e
inner join dbo.[Log] l on e.Username = l.Username
inner join dbo.Divisions d on e.DivisionCode = d.SapCode
group by d.DivisionShortcut, convert(varchar(10),l.DateTimeAccessing,120)

更新

以下是您加入日期的方法:

select d.DivisionShortcut, t.DateAccessing, count(distinct l.Username) as Cnt
from dbo.employee e
inner join dbo.[Log] l on e.Username = l.Username
inner join dbo.Divisions d on e.DivisionCode = d.SapCode
inner join (
  select distinct convert(varchar(10),DateTimeAccessing,120) as DateAccessing
  from dbo.Divisions
) t on t.DateAccessing = convert(varchar(10),l.DateTimeAccessing,120)
group by d.DivisionShortcut, t.DateAccessing

答案 1 :(得分:1)

试试这个

SELECT  cast(L.DateTimeAccessing as DATE) DateTimeAccessing
    ,D.DivisionShortcut
    ,count(distinct L.Username) as Cnt
    FROM dbo.employee E
    INNER JOIN dbo.[Log] L on E.Username = L.Username
    INNER JOIN dbo.Divisions D on E.DivisionCode = D.SapCode
    GROUP BY cast(L.DateTimeAccessing as DATE),D.DivisionShortcut