我想根據職位創建組織層次結構的報告。層次結構有4個層次,位置總是最後一層,但路徑不一定是4層。跳過數據爲NULL的重複捲起的行
例如:
公司>位置
公司>科>系>位置
我想獲得的人員數量。
declare @hierarchy table
(
Company nvarchar(50),
Section nvarchar(50),
Department nvarchar(50),
Unit nvarchar(50),
Position nvarchar(50),
Person nvarchar(50)
)
insert into @hierarchy values
('WD', 'Weapons', 'IT', 'officer', null, 'Wile E.'),
('ACME', 'Weapons', 'IT', 'Network', 'engineer', 'Brain'),
('ACME', 'Weapons', 'IT', 'Network', 'support', 'Pinky'),
('ACME', 'Weapons', 'IT', 'officer', null, 'Bugs'),
('ACME', 'Weapons', 'IT', 'officer', null, 'Elmer'),
('ACME', 'Weapons', 'IT', 'officer', null, 'Daffy'),
('ACME', 'Weapons', 'tech', null, null, 'Sylverster'),
('ACME', 'Anvils', 'officer', null, null, 'Road')
select Company, Section, Department, Unit, Position, count(Person) from @hierarchy
group by rollup(Company, Section, Department, Unit, Position)
在上面的例子中,我得到了同樣的3行的WD(西部數據,砧,官,NULL,NULL),其中一個就足夠了,因爲單位和位置是不適用的。
但是,如果我在查詢放distinct
,我得到一個看似不錯的結果
select distinct Company, Section, Department, Unit, Position, count(Person) from @hierarchy
group by rollup(Company, Section, Department, Unit, Position)
什麼我不知道的是,如果這只是一些黑客,我真的很幸運,或者如果它是一個正確的方法解決這個問題?
請加期待的結果 – Backs
@backs:如果您運行的查詢用戶提供有重複的行,用戶並不希望這些重複使用 – TheGameiswar
'集團BY'爲每列然後使用'聯盟所有' – NEER