提出这个问题的最佳方式是,如果我举一个例子说明我拥有的东西以及我想要得到的东西。 我有一张表格,显示所有经理,这些经理下的所有主管以及这些主管下的所有员工。我想要得到的是提供相同的信息,但形成的方式是管理者和主管不会像现在的表一样重复。 所以,这是原始表:
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
所以,基本上,我在这里要做的是避免重复管理者和/或主管的名字。 我在Excel中完成了这个但是使用了PIVOT,但我不确定我能在SQL Server中做同样的事情,因为TSQL的PIVOT要求我聚合数据而我在这里没有这样做。此外,我觉得应该有一个更简单的方法来做到这一点。 有没有人有想法?感谢!!!
答案 0 :(得分:0)
试试这个:
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