汇总 view/categorized 显示...可能是枢轴?

Summarized view/categorized display...possibly pivot?

问这个问题的最佳方式是,如果我给你一个例子,说明我拥有什么以及我想要得到什么。 我有一个 table 显示所有经理,这些经理下的所有主管和这些主管下的所有员工。我想要得到的是呈现相同的信息,但其格式不会像我当前的 table 中那样重复经理和主管。 所以,这是原来的 table:

Manager  Supervisor Employee Employee's Title Employee Name
John Smith Pete Adams 15352  Analyst   Tiffany Johnson
John Smith Pete Adams 43543  Developer  David Jackson
John Smith Pete Adams 54553  Programmer  Mike Dudley
John Smith Patricia Salomon36656  Analyst   Josh Adkins
John Smith Patricia Salomon5676  Developer  Beth Davidoff
John Smith Patricia Salomon78568  Programmer  Rick Tyler
Jody Melito Ana Carlisle 6783  Architect  Justin Acevedo
Jody Melito Ana Carlisle 1747  Designer  Joey Smith

这就是我想要得到的:

Manager  Supervisor     Employee   Employee's Title   Employee Name Total
John Smith Pete Adams     15352    Analyst     Tiffany Johnson 3
                43543    Developer        David Jackson 
                54553    Programmer    Mike Dudley 
      Patricia Salomon36656    Analyst        Josh Adkins     3
                5676    Developer        Beth Davidoff 
                78568    Programmer    Rick Tyler 
Jody Melito Ana Carlisle    6783    Architect        Justin Acevedo 2
                1747    Designer        Joey Smith

所以,基本上,我在这里想做的是避免重复经理 and/or 主管的名字(如果他们重复的话)。 我在 Excel 中完成了此操作,但使用 PIVOT 但我不确定我是否可以在 SQL 服务器中执行相同的操作,因为 TSQL 的 PIVOT 要求我聚合数据并且我在这里不这样做。另外,我觉得应该有一种更简单的方法来做到这一点。 有人有想法吗?谢谢!!!

试试这个:

with dat as (
  select * 
       , rn1 = row_number() over (partition by manager order by employee)
       , cnt1 = count(*) over (partition by manager)
       , rn2 = row_number() over (partition by manager, Supervisor order by employee)
       , cnt2 = count(*) over (partition by manager, Supervisor)
  from ( 
    values ('John Smith','Pete Adams','15352')
         , ('John Smith','Pete Adams','15353')
         , ('John Smith','Patricia Salomon','36656')
         , ('John Smith','Patricia Salomon','36658')
    ) yt (Manager,Supervisor,Employee)
)
select manager1    = case when rn1 = 1 then manager else null end
     , managerC    = case when rn1 = 1 then cnt1 else null end
     , supervisor1 = case when rn2 = 1 then supervisor else null end      
     , supervisorC = case when rn2 = 1 then cnt2 else null end      
     , *
from dat   
order by manager, rn1, supervisor, rn2, employee