如何发现员工部门变动?
How to find employee department changes?
我有一个table,里面有各个员工的旧部门和新部门:
EmployeeID
OldDept
NewDept
123
Design
Design
234
Software
Engineering
345
Design
Software
456
Advertising
Software
如何创建如下所示的 table:
Dept
TransfersIn
TransfersOut
Software
2
1
Design
0
1
Advertising
0
1
Engineering
1
0
您也许可以使用此查询来查找转出:
SELECT
OldDept AS Dept,
COUNTIF(OldDept != NewDept) As TransfersOut
FROM table
GROUPBY
EmployeeID,
OldDept,
NewDept
下面使用
select * from (
select NewDept as Department, count(*) Transfers, 'TransfersIn' Mode from your_table
where NewDept != OldDept
group by Department, Mode
union all
select OldDept as Department, count(*) Transfers, 'TransfersOut' Mode from your_table
where NewDept != OldDept
group by Department, Mode
)
pivot (sum(Transfers) for mode in ('TransfersIn', 'TransfersOut'))
如果应用于您问题中的示例数据 - 输出为
您可以使用两个子选择的 FULL OUTER JOIN
SELECT
COALESCE(OldDept,NewDept) AS Dept, IFNULL(TransfersIn,0) AS TransfersIn , IFNULL(TransfersOut) AS TransfersOut
FROM
(SELECT NewDept, COUNT(*) AS TransfersIn FROM tabl1 GROUP BY NewDept) As Ne
FULL OUTER JOIN
(SELECT OldDept, COUNT(*) AS TransfersOut FROM tabl1 GROUP BY NewDept) Ol
ON Ne.NewDept = Ol.OldDept
我有一个table,里面有各个员工的旧部门和新部门:
EmployeeID | OldDept | NewDept |
---|---|---|
123 | Design | Design |
234 | Software | Engineering |
345 | Design | Software |
456 | Advertising | Software |
如何创建如下所示的 table:
Dept | TransfersIn | TransfersOut |
---|---|---|
Software | 2 | 1 |
Design | 0 | 1 |
Advertising | 0 | 1 |
Engineering | 1 | 0 |
您也许可以使用此查询来查找转出:
SELECT
OldDept AS Dept,
COUNTIF(OldDept != NewDept) As TransfersOut
FROM table
GROUPBY
EmployeeID,
OldDept,
NewDept
下面使用
select * from (
select NewDept as Department, count(*) Transfers, 'TransfersIn' Mode from your_table
where NewDept != OldDept
group by Department, Mode
union all
select OldDept as Department, count(*) Transfers, 'TransfersOut' Mode from your_table
where NewDept != OldDept
group by Department, Mode
)
pivot (sum(Transfers) for mode in ('TransfersIn', 'TransfersOut'))
如果应用于您问题中的示例数据 - 输出为
您可以使用两个子选择的 FULL OUTER JOIN
SELECT
COALESCE(OldDept,NewDept) AS Dept, IFNULL(TransfersIn,0) AS TransfersIn , IFNULL(TransfersOut) AS TransfersOut
FROM
(SELECT NewDept, COUNT(*) AS TransfersIn FROM tabl1 GROUP BY NewDept) As Ne
FULL OUTER JOIN
(SELECT OldDept, COUNT(*) AS TransfersOut FROM tabl1 GROUP BY NewDept) Ol
ON Ne.NewDept = Ol.OldDept