具有COUNT

时间:2019-02-04 09:53:25

标签: sql-server

我有一张通讯表,其中包含;创建用户,创建日期和子代码。我希望输出在SSRS中有4列,显示上个月的通信;

Comms logged    Dealt With     % Dealt With
Created         User              1    
Created         User              2

到目前为止,我已经掌握了

SELECT
  [EM-COMMUNICATION].[CRT-USER]
  ,COUNT([EM-COMMUNICATION].[CRT-USER]) AS LOGGED
  ,(SELECT COUNT([EM-COMMUNICATION].[CRT-USER]) FROM [EM-COMMUNICATION] WHERE [EM-COMMUNICATION].[SUB-CODE] = N'DEALTWITH' AND DateDiff(MONTH,[EM-COMMUNICATION].[CRT-DATE],GetDate()) = 1) AS Dealt
FROM
  [EM-COMMUNICATION]
WHERE
  DateDiff(MONTH,[EM-COMMUNICATION].[CRT-DATE],GetDate()) = 1
GROUP BY
  [EM-COMMUNICATION].[CRT-USER]

我遇到的问题是,子查询返回的是所有用户的通信计数,而不是匹配主查询的分组,即,每行在'Dealt With'中具有相同的计数

1 个答案:

答案 0 :(得分:0)

您需要使用AND [EM-COMMUNICATION].[CRT-USER] = T.[CRT-USER]

将子查询与主查询相关联
SELECT
  [EM-COMMUNICATION].[CRT-USER]
  ,COUNT([EM-COMMUNICATION].[CRT-USER]) AS LOGGED
  ,(SELECT COUNT([EM-COMMUNICATION].[CRT-USER]) FROM [EM-COMMUNICATION] as T WHERE T.[SUB-CODE] = N'DEALTWITH' AND DateDiff(MONTH,T.[CRT-DATE],GetDate()) = 1 AND [EM-COMMUNICATION].[CRT-USER] =  T.[CRT-USER]) AS Dealt
FROM
  [EM-COMMUNICATION]
WHERE
  DateDiff(MONTH,[EM-COMMUNICATION].[CRT-DATE],GetDate()) = 1
GROUP BY
  [EM-COMMUNICATION].[CRT-USER]