sql - 跨行的 SQL DISTINCT 值
问题描述
我在列中有重复agreementnumber
和重复telephone
,我想获得唯一性agreementnumber
,并且它在列中是对应的唯一telephone
性。
我用 SQL 编写了查询,这给了我唯一agreementnumber
但telephone
行是重复的,但我想要唯一的电话号码。
代码:
select agreementnumber,
max(case when rn = 1 then telephone end) telephone1,
max(case when rn = 2 then telephone end) telephone2,
max(case when rn = 3 then telephone end) telephone3,
max(case when rn = 4 then telephone end) telephone4,
max(case when rn = 5 then telephone end) telephone5
from
(
select agreementnumber, telephone,
row_number() over(partition by agreementnumber order by telephone) rn
from alternate_mobile
) src
group by agreementnumber;
我想要以下输出。col1 和 col2,col3,col4,col4 中的唯一值。
col1 col2 col3 col4`` AGMTNO phone1 phone2 phone3
解决方案
请注意,您可以通过使用rank()
而不是减少子查询的数量row_number()
:
select agreementnumber,
max(case when rn = 1 then telephone end) as telephone1,
max(case when rn = 2 then telephone end) as telephone2,
max(case when rn = 3 then telephone end) as telephone3,
max(case when rn = 4 then telephone end) as telephone4,
max(case when rn = 5 then telephone end) as telephone5
from (select am.*,
rank() over (partition by am.agreementnumber order by am.telephone) as rn
from alternate_mobile am
) am
group by agreementnumber;
推荐阅读
- python - 通过repitition的python数组赋值
- javascript - 使用 vue-ctl 创建项目时被操作系统拒绝的操作
- css - CastError:模型“User”的路径“_id”处的值“app.css”转换为 ObjectId 失败
- reactjs - 如何修复 undefined 类型的错误参数不可分配给'string or () => string usng typescript 类型的参数并做出反应?
- css - 如何切换 css 类以与 setState Hook 做出反应
- javascript - 除去包含类的标签之外的 html 标签
- python - Kivy:如何更改模板中 TextInput 的 text_hint 值
- python - 如何在python的方法中重新迭代for循环?
- php - Laravel:在编辑表单中显示选定的值
- reactjs - 如何随着状态的变化而改变 DraftJS Editor 的初始内容?