Pivot Table 有条件
Pivot Table with a condition
想想我有一个这样的 table
ID DEPARTMENT
1 Production
1 IT
2 Sales
2 Marketing
2 Sales
我怎样才能得到如下结果
ID Production IT Sales Marketing
1 1 1 0 0
2 0 0 1 1
2 0 0 1 0
您会注意到,在 ID 号 2 'Sales' 的原始 table 中,部门是重复的,因此每当重复部门时,旋转的 table 中应该有另一个条目。
一种方法是在旋转之前添加 row_number。
然后枢轴将不只是按 ID 分组。
SELECT ID, Production, IT, Sales, Marketing
FROM
(
SELECT ID, DEPARTMENT
, ROW_NUMBER() OVER (PARTITION BY ID, DEPARTMENT ORDER BY ID) AS RN
FROM yourtable t
) Src
PIVOT
(
COUNT(*)
FOR DEPARTMENT IN (
'Production' AS Production,
'IT' AS IT,
'Sales' AS Sales,
'Marketing' AS Marketing
)
) Pvt
ID
PRODUCTION
IT
SALES
MARKETING
1
1
1
0
0
2
0
0
1
1
2
0
0
1
0
db<>fiddle here
想想我有一个这样的 table
ID DEPARTMENT
1 Production
1 IT
2 Sales
2 Marketing
2 Sales
我怎样才能得到如下结果
ID Production IT Sales Marketing
1 1 1 0 0
2 0 0 1 1
2 0 0 1 0
您会注意到,在 ID 号 2 'Sales' 的原始 table 中,部门是重复的,因此每当重复部门时,旋转的 table 中应该有另一个条目。
一种方法是在旋转之前添加 row_number。
然后枢轴将不只是按 ID 分组。
SELECT ID, Production, IT, Sales, Marketing
FROM
(
SELECT ID, DEPARTMENT
, ROW_NUMBER() OVER (PARTITION BY ID, DEPARTMENT ORDER BY ID) AS RN
FROM yourtable t
) Src
PIVOT
(
COUNT(*)
FOR DEPARTMENT IN (
'Production' AS Production,
'IT' AS IT,
'Sales' AS Sales,
'Marketing' AS Marketing
)
) Pvt
ID | PRODUCTION | IT | SALES | MARKETING |
---|---|---|---|---|
1 | 1 | 1 | 0 | 0 |
2 | 0 | 0 | 1 | 1 |
2 | 0 | 0 | 1 | 0 |
db<>fiddle here