如何在两个层面上进行调整

How to pivot on two levels

我正在使用 SQL Server 2012 并尝试根据下面的 table 从 TSQL 构建一个枢轴 table,它是通过连接多个生成的table秒。

INCIDENT ID | Department | Priority      | Impact 
--------------------------------------------
1           | IT         | Urgent        | High
2           | IT         | Retrospective | Medium   
3           | Marketing  | Normal        | Low
4           | Marketing  | Normal        | High
5           | Marketing  | Normal        | Med
6           | Finance    | Normal        | Med

从此table,希望它以下列格式显示:

Priority     | Normal              | Urgent              | Retrospective       |
| Department | Low | Medium | High | Low | Medium | High | Low | Medium | High |
--------------------------------------------------------------------------------
| IT         |   1 |      1 |    0 |   1 |      1 |    0 |   1 |      1 |    0 |
| Finance    |   0 |      0 |    1 |   1 |      1 |    0 |   1 |      1 |    0 |
| Marketing  |   0 |      1 |    0 |   1 |      1 |    0 |   1 |      1 |    0 |

我有以下代码,它成功地在 "Priority" 级别上进行了 Pivots。

SELECT *
FROM (
    SELECT 
        COUNT(incident.incident_id) OVER(PARTITION BY serv_dept.serv_dept_n) Total,
        serv_dept.serv_dept_n       Department,
        ImpactName.item_n           Impact,
        PriorityName.item_n         Priority    
    FROM --  ommitted for brevity
    WHERE  -- ommitted for brevity
) AS T

PIVOT (
    COUNT(Priority)
    FOR Priority IN ("Normal", "Urgent", "Retrospective")
) PIV
ORDER BY Department ASC

如何使此查询像我粘贴的第二个 table 那样在两个级别上进行转换? 任何帮助将不胜感激。

最简单的方法可能是条件聚合:

select department,
       sum(case when priority = 'Normal' and target = 'Low' then 1 else 0 end) as Normal_low,
       sum(case when priority = 'Normal' and target = 'Med' then 1 else 0 end) as Normal_med,
       sum(case when priority = 'Normal' and target = 'High' then 1 else 0 end) as Normal_high,
       . . .
from t
group by department;

我来试试看:

WITH PivotData AS
(
    SELECT
        Department
        , Priority + '_' + Impact AS PriorityImpact
        , Incident_ID
    FROM
        <table>
)
SELECT
    Department
    , Normal_Low
    , Normal_Medium
    ,...
FROM
PivotData
PIVOT (COUNT(Incident_ID FOR PriorityImpact IN (<Listing all the PriorityImpact values>) ) as P;