2016-02-29 160 views
0

我想創建一個視圖,它將返回一個3級數據的字符串。sql - 顯示祖父母,父母和孩子

select bf.functionName + ' \ ' + ISNULL(bf1.functionName + ' \ ', '') + ISNULL(bf2.functionName, '') from tblBusinessFunction bf 
inner join tblBusinessFunction bf1 on bf1.parentID = bf.id and bf.level = 0 
inner join tblBusinessFunction bf2 on bf2.parentID = bf1.id and bf1.level = 1 

以上只是返回頂級祖父母和父母,而不是子級別。

這就是表看起來像

| id | functionName    | parentID | level | 
|:-----|----------------------------:|:--------:|:-------:| 
| 101 | Portfolio Strategy Functions| NULL | 0 | 
| 110 | Research     | 101 | 1 | 
| 111 | Economic Forecasting  | 110 | 2 | 

現在我的查詢將返回Portfolio Strategy Functions \ Research \ Economic Forecasting,但我希望它也返回Portfolio Strategy Functions \ Research它不會做。

+0

這是一個偉大的地方開始。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –

+1

切換到「左連接」。並看看** recoursive CTE **。 –

+1

我在示例數據中看不到任何名爲'level'的字段。 –

回答

2

我試圖解決

declare @T table (id int, functionName varchar(50), parentid int, level int) 

insert @T 
values 
(101,'Portfolio Strategy Functions',null,0), 
(110,'Research',101,1), 
(111,'Economic Forecasting',110,2) 

;with Outline as 
(select id,level,functionName = convert(varchar(max),functionName) from @T where level = 0 
    union all 
    select T.ID, T.level, functionName = O.functionName +'/'+ T.functionName from @T T 
    join Outline O on O.id = T.parentid 
) 

select * from OutLine 
where level > 0 

這是導致

(3 row(s) affected) 
id   level  functionName 
----------- ----------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
110   1   Portfolio Strategy Functions/Research 
111   2   Portfolio Strategy Functions/Research/Economic Forecasting 

(2 row(s) affected) 
+0

謝謝!這工作作爲一個特別查詢。這將幫助我理解如何做到這一點,不幸的是我不能用它來生成視圖,但這是一個單獨的問題。 – whoisearth