我需要为父记录返回一行数据。父记录可以有很多子记录,但我只想要前两行(以及父记录的总行数)。
这是一个数据示例:
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 中使用它,但我从查询开始,然后从那里开始。
什么样的查询可以完成这个?
最佳答案
使用派生表对 childdata 表的行进行编号,并计算每个父级的 childid 的数量。 left join
到 parenttable 并得到想要的结果。
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
关于sql - 选择子表的前两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41495965/