当前组的历史总和

时间:2018-06-21 14:30:07

标签: sql sql-server

我有一个人的SQL数据库,我想从中查看每个人在特定部门有多少经验。

在当前查询中,我具有以下代码:

SELECT [PERSON_ID]
,sum(case when [DEPARTMENT] = 'Marketing' then 1 else 0 end) as Exp_Marketing
,sum(case when [FUNCTION_DESC] = 'Finance' then 1 else 0 end) as Exp_Finance
FROM [xxxx].[xxxx].[xxxx]
GROUP BY [PERSON_ID]

每个人在服务的月份中都有一行,因此拥有12个月的财务经验的人在Exp_Finance列中的值为12。

但是,问题在于结果现在显示了所有人的结果。也是已经离开组织的人。我如何确保结果仅显示组织中当前成员的历史信息。换句话说,实际上是在“日期”列中以“ 2018M06”作为值的行。

2 个答案:

答案 0 :(得分:1)

您应该在EXISTS子句中添加WHERE,这样才能只包括符合条件的人员。

SELECT [PERSON_ID]
,sum(case when [DEPARTMENT] = 'Marketing' then 1 else 0 end) as Exp_Marketing
,sum(case when [FUNCTION_DESC] = 'Finance' then 1 else 0 end) as Exp_Finance
FROM [xxxx].[xxxx].[xxxx] A
WHERE EXISTS (SELECT * FROM [xxxx].[xxxx].[xxxx] B
   WHERE A.PERSON_ID = B.PERSON_ID AND B.[DATE] = '2018M06')
GROUP BY [PERSON_ID]

答案 1 :(得分:1)

您可以使用having子句:

SELECT [PERSON_ID],
      sum(case when [DEPARTMENT] = 'Marketing' then 1 else 0 end) as Exp_Marketing,
      sum(case when [FUNCTION_DESC] = 'Finance' then 1 else 0 end) as Exp_Finance
FROM [xxxx].[xxxx].[xxxx]
GROUP BY [PERSON_ID]
HAVING MAX([DATE]) = '2018M06';

您的月份格式似乎可以使用MAX()