0
我試圖在我的表中創建一個名爲Owner的字段,其中您選擇了AddedBy字段,其中parentID等於PostID到目前爲止它只打印出第一個字段,第二個始終爲空。我在查詢中做一個子查詢。我試着去獲取父AddedBy場通過字段獲得父項的子查詢
SELECT Level, Sequence, PostID, AddedBy, Title, ParentID, Path_String,
CASE WHEN ParentID IS NULL THEN
AddedBy
ELSE
(SELECT AddedBy FROM cte o WHERE o.PostID = ParentID)
END AS Owner
FROM cte order by Sequence
我試着去獲取有關通過PARENTID在joinded的帖子ID的所有帖子的計數的加入,但IM得到一個錯誤,所以,當我通過做一組中的所有場我仍然得到錯誤: - 錯誤下面是
SELECT s.Level, s.Sequence, s.PostID, s.AddedBy,
s.Title, s.ParentID, s.Path_String,
Owner = COALESCE(o.AddedBy, s.AddedBy), COUNT(r.ParentID)
FROM cte AS s
LEFT OUTER JOIN cte AS o
ON s.ParentID = o.PostID
RIGHT join cte AS r
on s.PostID = r.ParentID
ORDER BY s.Sequence;
我得到以下錯誤:
Msg 8120, Level 16, State 1, Procedure sproc_GetPostsByThread, Line 34
Column 'cte.Level' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause.
帖子ID,PARENTID,AddedBy,標題,Path_String: - 是帖子ID IdentityColumn Path_String我S IN此格式1/1/1 /,1/1/2和PARENTID是整數
Level Sequence PostID AddedBy Title ParentID Path_String Owner Count
1 00000003 3 kirkdm test NULL 3/ kirkdm 1
2 0000000300000005 5 MikeDM re: test 3 3/5/ kirkdm 2
3 000000030000000500000008 8 Joelene re: test 5 3/5/8/ MikeDM 2
3 000000030000000500000009 9 kirkdm re: test 5 3/5/9/ MikeDM 1
4 00000003000000050000000900000010 10 Crushanin re: test 9 3/5/9/10/ kirkdm 1
應該是這
Level Sequence PostID AddedBy Title ParentID Path_String Owner Count column here
1 00000003 3 kirkdm test NULL 3/ kirkdm
2 0000000300000005 5 MikeDM re: test 3 3/5/ kirkdm
3 000000030000000500000008 8 Joelene re: test 5 3/5/8/ MikeDM
4 00000003000000050000000800000014 14 Christian re: test 8 3/5/8/14/ Joelene
4 00000003000000050000000800000015 15 Zeke re: test 8 3/5/8/15/ Joelene
3 000000030000000500000009 9 kirkdm re: test 5 3/5/9/ MikeDM
4 00000003000000050000000900000010 10 Crushanin re: test 9 3/5/9/10/ kirkdm
5 0000000300000005000000090000001000000011 11 Tim re: test 10 3/5/9/10/11/ Crushanin
完美謝謝你,因爲你已經到了。我在過去幾天中學到了很多關於SQL的新知識 – ONYX
請您向我解釋COALESCE – ONYX
'COALESCE'返回第一個非空表達式。所以左連接將顯示所有者作爲來自父行的AddedBy值(如果存在);如果不是,它將使用當前行中的AddedBy值。有關'COALESCE'的更多詳細信息,請參閱此聯機叢書主題:http://msdn.microsoft.com/en-us/library/ms190349.aspx –