I have the code below created that provides me with a count of unique users broken down by company. I would like to add a date modifier that would have two columns, one for “Last Week” and one for “2 Weeks Ago”. I would like these columns to respectively show active users for the previous week’s dates and the week prior to that based off the field “users.date”. Any help would be fantastic. I am using SQL Server Management Studio 2008 R2.
--Active Users
SELECT company.companyName as 'Group Name',
COUNT(distinct users.userid) [Count]
FROM Users, Company
WHERE
Jobstate = '6'
and company.companyID = users.companyid
and company.companyID in (1,4,31)
GROUP BY company.companyName
Currently I am receiving this as a result:
Group Name | Count |
------------------------
Company 1 | 104 |
Company 2 | 74 |
Company 3 | 46 |
What I would like to see would be:
Group Name | Last Week | 2 Weeks Ago |
--------------------------------------
Company 1 | 14 | 16 |
Company 2 | 7 | 12 |
Company 3 | 4 | 8 |
For SQL Server it would look something like this.
EDIT: The query above counts users, not distinct users. If you want distinct users for the last week it can be done very simply by modifying your original query.
If you want to combine the two so you have all the columns in a single dataset it can be done by combining the two approaches like this:
SQLFiddle here