0

我创建了下面的代码,它为我提供了按公司细分的唯一用户数。我想添加一个日期修饰符,它有两列,一列用于“上周”,另一列用于“2 周前”。我希望这些列根据字段“users.date”分别显示前一周日期和前一周的活跃用户。任何帮助都会很棒。我正在使用 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

目前我收到这个结果:

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

对于 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在这里

于 2012-11-27T15:12:05.727 回答