将“上周”和“2周前”添加到SQL查询中

时间:2012-11-27 15:05:27

标签: sql sql-server sql-server-2008-r2

我创建了以下代码,为我提供了按公司细分的唯一身份用户数。我想添加一个日期修饰符,它有两列,一列用于“上周”,一列用于“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           |

1 个答案:

答案 0 :(得分: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