0

我是 ASP.NET 中使用 C# 的新开发人员。我为其中一家公司开发了一个基于 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 值。为什么?以及如何解决?

4

2 回答 2

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
于 2012-11-21T08:12:02.787 回答
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
于 2012-11-21T08:44:32.373 回答