简体   繁体   中英

SQL Server query hierarchical results using a CTE

I have an emp table like this:

在此处输入图片说明

I need to group by DeptNo and JOB .

I am using the following code to generate group by

;With Cte as
(
    select 
        DeptNo, Count(EMPNO) Total 
    from 
        Emp 
    group by 
        DeptNo

    union all 

    select  
        DeptNo, Count(EMPNO) Total 
    from 
        Emp 
    group by 
        DeptNo, Job 
) 
select * 
from Cte 
order by DeptNo, Total desc

But I need to make the output as below

在此处输入图片说明

Is there any option to generate similar results in SQL with dynamic CTE?

Thanks

SELECT x.DeptNo AS [Dept/Job], COUNT(*) AS Cnt, x.DeptNo, 1 AS RowType
FROM dbo.emp x
GROUP BY x.DepNo

UNION ALL 

SELECT y.Job, COUNT(*), y.DepNo, 2 AS RowType
FROM dbo.emp y
GROUP BY y.Job, y.DepNo

ORDER BY DepNo, RowType

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM