sql - 选择子表的前两行

标签 sql sql-server

我需要为父记录返回一行数据。父记录可以有很多子记录,但我只想要前两行(以及父记录的总行数)。

这是一个数据示例:

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/

相关文章:

mysql - 按行级别的 SQL 过滤器

php - 需要有关复杂嵌套查询的专家建议

sql - 仅从同一用户中选择最多 3 行 - MySQL

sql-server - 删除带有特殊字符的表名

sql - SYSDATETIME() 是否比 GETDATE() 花费更多?

java - 带有可能的单引号的 ExecuteUpdate

mysql - 混合使用的数据库索引中的字段顺序

MySQL - 另一种减少连接数量的方法? - 或简写语法

sql - DB中的存储函数和 View 有什么区别?

c# - 如何将空值传递给 SqlCommand 的参数