开发者社区 问答 正文

关于去重复记录的sql

现在有一个视图如图,现在我想要vessel_cn这一列不允许重复,如果重复则取seain列大的那一条记录,如果seain列的值相同则取seaout列大的那一条记录,如果seaout列值相同则取leng列大的那一条记录,不可能出现两列完全相同的情况。 比如图中第135 136行记录的vessel_cn值相同,所以应该去掉seain值小的135行。 求写sql语句对这个视图进行上述去重复选择。视图名叫v_plan image.png

展开
收起
长安归故里. 2020-01-07 21:23:27 1034 分享 版权
1 条回答
写回答
取消 提交回答
  • 方式一:试试用max聚合: 顺序:max聚合leng-->max聚合seaout-->max聚合seain sql如下: select C.vessel_cn,C.seain,C.maxSeaout,C.maxLength,max(C.seain) as maxSeain from ( select B.vessel_cn,B.seain,B.maxLength,max(B.seaout) as maxSeaout from ( select A.vessel_cn,A.seain,A.seaout,max(A.leng) as maxLength from 你的视图 A group by A.vessel_cn,A.seain,A.seaout ) B group by B.vessel_cn,B.seain,B.maxLength ) C group by C.vessel_cn,C.maxSeaout,C.maxLength

    (2)方案二:根据你列出的条件用子查询过滤掉重复的记录,sql: select A.vessel_cn,A.seain,A.seaout,A.leng from 你的视图 A where not exists (select 1 from 你的视图 B where B.vessel_cn=A.vessel_cn and B.seain=A.seain and B.seaout=A.seaout and B.leng>A.leng) and not exists (select 1 from 你的视图 C where C.vessel_cn=A.vessel_cn and C.seain=A.seain and C.seaout>A.seaout and C.leng=A.leng) and not exists (select 1 from 你的视图 D where D.vessel_cn=A.vessel_cn and D.seain>A.seain and D.seaout=A.seaout and D.leng=A.leng)

    2020-01-07 21:23:37
    赞同 展开评论
问答分类:
SQL
问答标签:
问答地址: