0

以下のコードを作成して、会社ごとに分類されたユニークユーザーの数を示しています。「先週」用と「2週間前」用の2つの列を持つ日付修飾子を追加したいと思います。これらの列には、「users.date」フィールドに基づいて、前の週の日付とその前の週のアクティブユーザーをそれぞれ表示したいと思います。どんな助けでも素晴らしいでしょう。SQL Server Management Studio2008R2を使用しています。

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

1 に答える 1

0

For SQL Server it would look something like this.

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

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.

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

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:

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

于 2012-11-27T15:12:05.727 に答える