I am a new developer in ASP.NET with C#. I developed a web-based application for one of the companies, and now I am required to develop a log that shows the number of unique people accessing the system. For example, Employees A and B from Division AA accessed the system today. Employee A accessed the system twice at the same day. The log should show that there are two employees from Division AA accessed the system today not three.
I have the following database design:
Employee Table: Username, Name, DivisionCode (DivisionCode is a foreign key to SapCode)
Divisions Table: SapCode DivisionShortcut
Log Table: ID, Username, DateTimeAccessing
I wrote the following query that shows the username, employee name, division and 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
The query should show the number of employees who accessed the system everyday based on division and date such as:
At Nove 21, Division AA = 2
Nove 21, Division BB = 7
Nove 20, Division AA = 12 and so on
So how to do that?
*UPDATE:*
I am using now the following query:
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
The problem now is for example if I want to see the statistics for today or Nov 10 for all divisions, the date column will show me NULL values for the division which have no employees accessing the system at that date. Why? And how to fix it?
Use
count(distinct)to count the number of users, andgroup byto group the result on divisons and dates.You can use
convertto get the date as a string from the datetime, but be aware that it slows down the query a bit.Update:
Here is how you can join in the dates: