我在SQL Server中有两个表。第一个表有一个成员名称列,第二个表有它们的亲属名称。我希望在单列中显示来自两个表的数据,如果成员有任何亲属,那么它必须立即显示在成员名称后的第二行中,如果成员不具有任何亲属,则必须只显示一行。例如,下面有第一个memebrsname表和他们的城市名
Regid Name City
----------------------------------------
1 Dr. Dharmesh Patel New york
2 Dr. Vivek Patel New york
3 Dr. Udayan Kachchhi New york
4 Dr. Geeti Maheshwari New york
5 Dr. SHANKAR DAYAL Arizona
6 Dr. Tejas Kakkad New york
7 Dr. TUSHAR PATEL California
8 Dr. Arpan Shah New york
9 Dr. AMI PATEL New york
和Relatives
表看起来像这样:
Regid Name City
-----------------------------------
6 MEETA KAKKAD New york
1 Aditya Patel New york
1 Namisha Patel New york
3 Dimple Kachchhi New york
4 Pankaj Maheshwari New york
8 Agastya Shah New york
8 Roma Shah New york
我希望显示这样的结果:
regid Name City
---------------------------------------------
1 Dr. Dharmesh Patel New york
1 Aditya Patel New york
1 Namisha Patel New york
2 Dr. Vivek Patel New york
3 Dr. Udayan Kachchhi New york
3 Dimple Kachchhi New york
4 Dr. Geeti Maheshwari New york
4 Pankaj Maheshwari New york
5 Dr. SHANKAR DAYAL Arizona
6 Dr. Tejas Kakkad New york
6 MEETA KAKKAD New york
7 Dr. TUSHAR PATEL California
8 Dr. Arpan Shah New york
8 Agastya Shah New york
8 Roma Shah New york
9 Dr. AMI PATEL New york
如何在SQL Server中获得以上结果?请帮忙
答案 0 :(得分:1)
使用row_number()
函数与union all
一起获取父记录下的子记录
select *,
row_number() over (partition by Regid order by Sort) Seq
from
(
select Regid, Name, City, 1 AS Sort from parent p
UNION ALL
select Regid, Name, City, 2 AS Sort from child c
)t
您还可以定义显式排序
select Regid, Name, City, 1 AS Sort from parent p
UNION ALL
select Regid, Name, City, 2 AS Sort from child c
order by RegId, Sort
答案 1 :(得分:0)
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
答案 2 :(得分:0)
您似乎正在为regid
订购的两个表寻找联合select Regid, Name, City
from table1
union
select Regid, Name, City
from table2
order by regid
答案 3 :(得分:0)
假设你要缩进亲属的名字。使用seq
确保该成员出现在他/她的亲属面前:
select Regid, Name, City
from
(
select 1 as seq, Regid, Name, City
from table1
union all
select 2, Regid,' ' + Name, City
from table2 ) t
order by seq, Regid