根据外观透视数据

时间:2017-07-14 08:30:24

标签: sql-server tsql sql-server-2012 pivot

我希望为部门的每个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

输出

enter image description here

预期输出:

Service_Number ABC XYZ PQR
12A            1   1    0
12B            1   0    0
12C            0   1    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 |
+----------------+-----+-----+-----+