简体   繁体   English

SQL Server使用CTE查询分层结果

[英]SQL Server query hierarchical results using a CTE

I have an emp table like this: 我有一个这样的emp表:

在此处输入图片说明

I need to group by DeptNo and JOB . 我需要按DeptNoJOB分组。

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? 是否可以通过动态CTE在SQL中生成类似结果?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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