2017-01-05 87 views
2

我需要爲父記錄返回一行數據。父記錄可以有許多子記錄,但我只需要前兩行(以及父行的總計數)。選擇前兩行子表

下面是數據的一個例子:

ParentTable 
+-----------------------+ 
| ParentId | ParentData | 
+-----------------------+ 
|  1| Stuff  | 
|  2| Things  | 
|  3| Foo   | 
|  4| Bar   | 
------------------------- 

ChildTable 
+-------------------------------+ 
| ChildId | ParentId| ChildData | 
+-------------------------------+ 
|  1 |  1 | Alpha  | 
|  2 |  1 | Bravo  | 
|  3 |  2 | Charlie | 
|  4 |  2 | Delta  | 
|  5 |  2 | Echo  | 
|  6 |  3 | Foxtrot | 
--------------------------------- 

這裏是我想要的結果:

+-----------------------------------------------------------------+ 
| ParentId | ParentData | ChildData1 | ChildData2 | ChildRowCount | 
+-----------------------------------------------------------------+ 
|  1 | Stuff  | Alpha  | Bravo  |    2 | 
|  2 | Things  | Charlie | Delta  |    3 | 
|  3 | Foo  | Foxtrot | (NULL)  |    1 | 
|  4 | Bar  | (NULL)  | (NULL)  |    0 | 
------------------------------------------------------------------- 

我不知道這需要一個子查詢,臨時表,或某種JOIN或GROUP BY。

最後我需要在SSIS中使用它,但是我先從查詢開始並從那裏開始。

什麼樣的查詢可以做到這一點?

+1

您正在使用哪些DBMS? –

+0

由於提到了SSIS而添加了SQL Server ...請使用*特定的*適當的標籤進行標記。 –

+0

*前2行*如何?什麼指定了從子表中拾取的2條記錄? –

回答

3

使用派生表對子數據表的行進行編號並計算每個父級的子級ID的數量。 left join這對於父級,並得到所需的結果。

select distinct p.parentid,p.parentdata, 
max(case when c.rnum =1 then c.childata end) over(partition by p.parentid,p.parentdata) as childdata1, 
max(case when c.rnum =2 then c.childata end) over(partition by p.parentid,p.parentdata) as childdata2, 
coalesce(c.childrowcount,0) as childrowcount 
from parenttable p 
left join (select c.* 
      ,row_number() over(partition by parentid order by childid) as rnum 
      ,count(*) over(partition by parentid) as childrowcount 
      from childtable c) c 
on c.parentid=p.parentid 
+0

這是一個很好的解決方案。我得到了正確的「ChildData1」,「ChildData2」和「ChildRowCount」值,但這些行不是分組。因此,從問題的示例數據中,我有三行ParentId = 2.我試圖在整個語句的末尾使用「GROUP BY」,但我不確定要包含哪些列。我可以在GROUP BY中使用別名嗎? –

+0

使用'distinct'..我忘了包括它..看編輯.. –

+0

就是這樣。感謝您的回覆,@vkp。 –