如何在两个级别上转动

时间:2016-06-28 01:41:17

标签: sql-server database tsql pivot relational-database

我正在使用SQL Server 2012,并且正在尝试根据下表创建一个数据透视表,该表是通过连接多个表生成的。

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

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

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 |

我有以下代码成功地在"优先级"水平。

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

如何让这个查询在两个级别上进行透视,比如我粘贴的第二个表格? 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

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

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;

答案 1 :(得分:1)

我会抓住它:

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;