我希望为部门的每个service_number获取标志。为此,我写了以下PIVOT函数,但它不符合我的预期输出
DECLARE @MyTab TABLE
(
Service_Number VARCHAR(20),
Department VARCHAR(20)
)
INSERT INTO @MyTab VALUES ('12A','ABC'), ('12A','XYZ'), ('12B','ABC'), ('12C','PQR')
SELECT * FROM @MyTab
SELECT
[ABC],[xyz],[pqr]
FROM @MyTab
PIVOT( MAX(Service_Number)
FOR Service_Number IN ([ABC],[xyz],[pqr])) AS P
输出:
预期输出:
Service_Number ABC XYZ PQR
12A 1 1 0
12B 1 0 0
12C 0 1 1
答案 0 :(得分:0)
您需要更改枢轴部分,如下所示:
SELECT * from
(Select Service_Number, Department FROM @MyTab ) a
PIVOT( Count(Department) FOR Department IN ([ABC],[xyz],[pqr])) AS P
Service_Number没有[ABC],[xyz] ...
输出如下:
+----------------+-----+-----+-----+
| Service_Number | ABC | xyz | pqr |
+----------------+-----+-----+-----+
| 12A | 1 | 1 | 0 |
| 12B | 1 | 0 | 0 |
| 12C | 0 | 0 | 1 |
+----------------+-----+-----+-----+