计算每个组的变更数量

huangapple go评论60阅读模式
英文:

Count Number Of Changes Per Group

问题

我想要这个结果:

Manager_Change_Counter Employee
5 1
4 2

我需要统计每位员工在项目经理变更方面的次数,不考虑项目数量。

英文:

Given this data:

Project Manager Project Num Employee
A 1 1
A 2 1
B 3 1
A 4 1
B 5 1
B 6 1
A 7 1
A 8 1
B 9 1
A 1 2
B 2 2
B 3 2
A 4 2
A 5 2
B 6 2
A 7 2

I want This Result :

Manager_Change_Counter Employee
5 1
4 2

I need to count per employee how many project manger changes made regardless of number of projects

答案1

得分: 0

以下是已翻译的内容:

可以通过使用窗口函数 lag() 来实现这一目标,以检索上一行并确定是否已更改项目经理,然后计算更改的总时间:

WITH CTE AS (
  SELECT Employee,
       Project_Manager,
       lag(Project_Manager, 1, Project_Manager) OVER (PARTITION BY Employee ORDER BY Project_Num) AS PREV_Project_Manager
  FROM mytable
)
SELECT Employee, SUM(CASE WHEN Project_Manager = PREV_Project_Manager THEN 0 ELSE 1 END) AS Manager_Change_Counter
FROM CTE
GROUP BY Employee

结果:

Employee    Manager_Change_Counter
1           5
2           4

演示在此处

英文:

This can be accomplished by using the window function lag() to retrieve the previous row and determine whether or not Project Manager has been changed, then calculating the total time of changes :

WITH CTE AS (
  select Employee,
       Project_Manager,
       lag(Project_Manager, 1, Project_Manager) over (partition by Employee order by Project_Num) as PREV_Project_Manager
  from mytable
)
SELECT Employee, SUM(case when Project_Manager = PREV_Project_Manager then 0 else 1 end) as Manager_Change_Counter
from CTE
GROUP BY Employee

Result :

Employee	Manager_Change_Counter
1	        5
2	        4

Demo here

huangapple
  • 本文由 发表于 2023年5月10日 16:50:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76216529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定