首页 > 解决方案 > 如何通过 ID 连接一个表中的 2 行

问题描述

我需要对同名(同名但personal_identidy_code不同的人)进行统计。我想将 2 行或更多行加入 1 行,以便我可以继续将数据与 CASE 语句进行比较。

可以说,我有一个这样的查询输出:

acitivityNR  acitivityName  Personal_identity_code    Name
111             test             00000000001          hello wor
111             test2            00000000002          hello wor
111             test2            00000000002          hello wor
222             asd              11111111111          my name
222             asd2             11111111112          my name

可以有超过 2 行具有相同的 activityNR(activityName 可以不同)。我的输出中有超过 1 个活动。我需要比较,如果在activityNr 111 中有同名但不同的个人身份代码的人。我有想法将这些行合并为一个,所以我有这样的输出:

acitivityNR = aNR
acitivityName = aName
Personal_identity_code = code

aNR Aname Code         Name       Code2     Name2      Code3      Name3
111 test 00000000001 hello wor 00000000002 hello wor 00000000002 hello wor
222 asd  11111111111 my name   11111111112  my name

从那里我可以使用 CASE 语句来过滤掉 code = code2 = code3 的输出

这就是我所拥有的,还有一些 where 句子,但现在这并不重要。

select a.activityNR, a.activityName, p.prsonal_identity_code, p.name
from things t
inner join activitys a on t.id = a.things_id
inner join activitys_people ap on a.id = ap.activitys_id
inner join people p on ap.people_id = p.id
order by a.activityNR asc

标签: sqloracle

解决方案


select a1.activityNR, a1.activityName, a1.prsonal_identity_code,
       a2.activityName, a2.prsonal_identity_code
from activitys a1
  inner join activitys a2 on a1.acitivityNR = a2.acitivityNR
where a1.prsonal_identity_code <> a2.prsonal_identity_code

这将为您提供如下结果:

aNR Aname Code         Name       Code2     Name2
111 test 00000000001 hello wor 00000000002 hello wor
111 test 00000000001 hello wor 00000000002 hello wor
222 asd  11111111111 my name   11111111112  my name

推荐阅读