2012-11-27 70 views
0

我創建了下面的代碼,該代碼爲我提供了按公司細分的唯一用戶數。我想添加一個日期修飾符,它會有兩列,一列用於「上週」,另一列用於「2周前」。我希望這些列分別顯示前一週日期的活躍用戶和基於字段「users.date」之前一週的活動用戶。任何幫助都會很棒。我正在使用SQL Server Management Studio 2008 R2。將「上週」和「2周前」添加到SQL查詢

--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 

目前我收到這個結果:

Group Name | Count  | 
------------------------ 
Company 1 | 104  | 
Company 2 | 74  | 
Company 3 | 46  | 

我想看到的是:

Group Name | Last Week | 2 Weeks Ago | 
-------------------------------------- 
Company 1 | 14  | 16   | 
Company 2 | 7   | 12   | 
Company 3 | 4   | 8   | 
+0

SQL服務器= ['DATEDIFF()'](http://msdn.microsoft.com/en-us/library/ms189794.aspx),MySQL = ['DATEDIFF'](http://dev.mysql.com/doc/refman /5.5/en/date-and-time-functions.html#function_datediff)和其他口味有類似的東西。從那裏,關於如果結果是7天的<=7 days or >,要知道命名比較。 –

回答

0

對於SQL Server會是這個樣子。

SELECT 
    Company.CompanyName AS [Group Name], 
    COUNT(DISTINCT Users.UserId) AS [Count], 
    SUM (CASE 
     WHEN DATEDIFF(day, Users.Date, GETDATE()) < 7 THEN 1 
     ELSE 0 
     END 
    ) AS [Last Week] 
    -- Additional columns for last 2 weeks, etc. 
FROM Users, Company 

WHERE 
    Jobstate = '6' 
    AND Company.CompanyId = Users.CompanyId 
    AND Company.CompanyId in (1, 4, 31) 
GROUP BY 
    Company.CompanyName 

編輯:上述計數用戶,而不是不同用戶的查詢。如果您希望在上週使用不同的用戶,可以通過修改原始查詢來完成。

SELECT 
    Company.CompanyName AS [Group Name], 
    COUNT(DISTINCT Users.UserId) AS [Last Week] 
FROM Users, Company 

WHERE 
    Jobstate = '6' 
    AND Company.CompanyId = Users.CompanyId 
    AND Company.CompanyId in (1, 4, 31) 
    AND DATEDIFF(day, Users.Date, GETDATE()) < 7 
GROUP BY 
    Company.CompanyName 

如果你想兩個讓你擁有所有列在一個單一的數據集可以通過兩種方法類似這樣的結合來完成合並:

SELECT 
    Company.CompanyName AS [Group Name], 
    COUNT(DISTINCT Users.UserId) AS [Count], 
    COUNT (DISTINCT 
      CASE 
      WHEN DATEDIFF(day, Users.Date, GETDATE()) < 7 THEN Users.UserId 
      ELSE NULL 
      END 
     ) AS [Last Week] 
    -- Additional columns for last 2 weeks, etc. 
FROM Users, Company 

WHERE 
    Jobstate = '6' 
    AND Company.CompanyId = Users.CompanyId 
    AND Company.CompanyId in (1, 4, 31) 
GROUP BY 
    Company.CompanyName 

SQLFiddle here

+0

也許我錯過了一些東西,但這似乎並沒有產生準確的結果。以下是它返回的數據: '組名| Count |上週|' '--------------------------------' '公司1 | 12 | 412 |' '公司2 | 16 | 308 |' '公司3 | 55 | 629 |' 計數應該是不同用戶的總數,上週應該只是那周出現的不同用戶的計數,因此「上週」不應該高於「計數」 –

+0

對不起,我沒有正確理解問題。第一個查詢統計用戶,而不是不同的用戶。如果您希望上週有不同的用戶,那麼您可以輕鬆調整原始查詢。請參閱編輯。 – njr101

+0

非常感謝njr101。您編輯的查詢產生了我所需要的結果。這肯定會幫助我繼續進行任何額外的查詢! –