sql - 从 SQL 中的列中删除重复值
问题描述
我有两个表A
( group_id, id, subject
) 和B
( id, date
)。下面是表A和B在id上的联表。我尝试使用 distinct 和 partition 仅删除 group_id(field) 中的重复项,但没有运气:
我的代码:
select
a.group_id, a.id, a.subject, b.date
from
A a
inner join
(select
b.*,
row_number() over (partition by group_id order by date asc) as seqnum
from
B b) b on a.id = b.id and seqnum = 1
order by
date desc;
运行代码时出现此错误:
在第 1 行的 'partition by group_id order by date asc) as seqnum from B' 附近的查询中不能单独使用分区
这是我的预期结果:
先感谢您!
解决方案
看起来您想要显示的表格中每一行的最早日期。您的问题提到了两张表,但您只显示了一张。
我建议在大多数数据库中使用相关子查询:
select b.*
from b
where b.date = (select min(b2.date)
from b b2
where b2.group_id = b.group_id
);
我懂了。你需要join
先然后使用row_number()
:
select ab.*
from (select a.group_id, a.id, a.subject, b.date,
row_number() over (partition by a.group_id order by b.date) as seqnum
from A a join
B b
on a.id = b.id
) ab
where seqnum = 1
order by date desc;
推荐阅读
- database - 撇号不会保存在数据库中
- javascript - 是否可以在 JS 中将语言环境字符串转换为带有千位分隔符的十进制数?
- php - 非常坚持正则表达式
- java - 如何使用 PDFBox 确定实际 PDF 内容的位置?
- angular - 检测是否可以在 adaljs-angular4 中进行静默登录
- javascript - 将输入从 component.html 发送到 component.ts
- c# - 在指定 X 值处向 MSChart 添加数据点或绘制椭圆
- javascript - JavaScript - babel-preset-env 不为 IE11 转换箭头函数
- iis - 停止 IIS 解码 URL 中的 %2f
- variables - Julia中变量名称的分数