2017-08-30 15 views
3

我有一張配偶和子女連接到主用戶的表。當子選擇的數量未知時自加入

+----------------+-------------------+----------+------------------------------+------------------+ 
| Id | User_ID   | Rel_Type | Applno      | RelationWith  | 
+----------------+-------------------+----------+------------------------------+------------------+ 
|  1234756 | aambu ghosha  | self  | 201708180921  | aambu ghosha  | 
|  1235146 | parvati ghosha | spouse | NULL | aambu ghosha  | 
|  1235147 | ananta ghosha | Children | 201708180921  | aambu ghosha  | 
|   500787 | anant01011975  | self  | 20170811171403999L | anant01011975 | 
|   501626 | chandu1988  | children | NULL       | anant01011975 | 
|  1706064 | atmaram sutar  | self  | 20170821094537517L | atmaram sutar | 
|  1706494 | venu sutar  | spouse | 20170821094537517L | atmaram sutar | 

在上面的例子中,主申請人「aambu ghosha」是「自我」(主申請人)。配偶和子女(parvati和ananta)需要被視爲一個申請人。

aambu ghosha 3 
anant01011975 2 
atmaram sutar 2 

主要申請人的人數應該包括他們的家庭成員。預期結果如上所示。 我想這可以實現使用自我加入,但我不知道有多少孩子被鏈接到主申請人。找到計數的最佳方法是什麼?

http://sqlfiddle.com/#!9/30945c/2/0


更新:

如何自行 - 加入和更新鏈接到主申請人的申請號?對於例如第二個記錄NULL值應更改爲201708180921.

+0

請求的結果允許多少層次?只有一個? –

+0

是的。只允許1個級別,但頭部可以有多個家屬。 – shantanuo

回答

4

假設你有孩子的只是一個水平,這將工作

SELECT userid, count(*) 
FROM tab p 
JOIN tab ch ON p.user_id = ch.RelationWith 
WHERE p.user_id = p.RelationWith 
GROUP BY userid 

其實,即使簡單的查詢產生由你

SELECT RelationWith, count(*) 
FROM tab 
GROUP BY RelationWith