sql - 如何通过 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
解决方案
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
推荐阅读
- javascript - Cloudflare worker 用于重定向、无限循环
- docker - Apache Druid - 用于 arm 架构的 docker 构建
- amazon-web-services - ssh:连接到主机 18.116.70.233 端口 22:连接超时
- r - 是否可以在查看器窗格中查看乳胶表?
- shopware - Shopware 6 - 从产品存储库中获取与特定销售渠道相关联的产品
- c# - 分配“dd/MM/yyyy”数据时的日期时间,但它保存为“MM/dd/yyyy”
- virtual-machine - 如何调试来自虚拟机的连接
- python - 将类映射到 Pandas 一种热编码
- javascript - 如何使用相同的代码使网站更加动态/保存?
- typescript - aws:不允许外部使用带有前缀的标签键名