我在 SQL Server 中有下表:
| 體驗 ID | 員工ID | 體驗型別 |
|---|---|---|
| 1 | 1 | '作業' |
| 2 | 1 | '內部的' |
| 3 | 2 | '內部的' |
| 4 | 3 | '外部的' |
| 5 | 3 | '外部的' |
只有 3 個可能的值ExperienceType:“作業”、“內部”和“外部”
我想知道每個員工有多少每種型別的經驗:
| 員工ID | 作業經驗 | 內部經驗 | 外部經驗 |
|---|---|---|---|
| 1 | 1 | 1 | 0 |
| 2 | 0 | 1 | 0 |
| 3 | 0 | 0 | 2 |
我試過這個
select EmployeeId, count(*)
from EmployeeExperiences
group by EmployeeId
但這只給了我每個員工的經驗總數,我不知道如何按 ExperienceType 分解。
uj5u.com熱心網友回復:
一種方法是使用條件聚合(CASE WHEN在聚合函式內部)。
select
employeeid,
count(case when experiencetype = 'Work' then 1 end) as work_exp,
count(case when experiencetype = 'Internal' then 1 end) as internal_exp,
count(case when experiencetype = 'External' then 1 end) as external_exp
from employeeexperiences
group by employeeid
order by employeeid;
另一種選擇是使用PIVOT從句。
uj5u.com熱心網友回復:
PIVOT 的結果:
select EmployeeId, [Work], [Internal], [External] from (
select EmployeeId, ExperienceType from EmployeeExperiences) as SourceTable
pivot (
count(ExperienceType ) for ExperienceType in ([Work], [Internal], [External])) as
PivotTable
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/418527.html
標籤:
上一篇:使用類似正則運算式的功能過濾表
下一篇:如何在更新中獲取選定列的值
