繁体   English   中英

如何避免 sql 中的列中的重复值

[英]How to avoid duplicated values in a column in sql

我正在使用下面的代码从两个表中获取数据。 但我可以在data1data2列中看到一些重复的值。


SELECT DISTINCT a.student_id,a.class,a.sub_id,
      stringagg(a.sub_num) OVER (PARTITION BY a.student_id, a.class, a.sub_id 
                           ORDER BY NLSSORT(a.sub_num, 'NLS_SORT=BINARY_CI') ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
                          ) AS data1,
      stringagg(b.date) OVER (PARTITION BY b.sub_id 
                        ORDER BY NLSSORT(b.date, 'NLS_SORT=BINARY_CI') ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
                          ) AS data2
from tsg_class a JOIN tsg_date b ON a.student_id = b.student_id
                                and a.class = b.class
                                and a.sub_id = b.sub_id
where a.student_id = 38147;

我的结果如下图所示:

在此处输入图像描述

Data1 和 Data2 具有重复的值,例如22**** 22**** 22**** 22**** 555555 555555 555555 555555001 001 7WW 7WW D04 D04 MS7 MS7

但我希望它像22**** 55555001 7ww D04 MS7

请建议。

您使用哪个数据库? PL/SQL 建议 Oracle,但那里没有stringagg function - 我们现在使用listagg 最近的 Oracle 版本支持listagg(distinct...)解决您的问题。

否则,首先select 表中的distinct值,然后将聚合应用于已经不同的数据集。


这就是你现在所拥有的:

SQL> select listagg(job, ',') within group (order by job) jobs from emp;

JOBS
--------------------------------------------------------------------------------
ANALYST,ANALYST,CLERK,CLERK,CLERK,CLERK,MANAGER,MANAGER,MANAGER,PRESIDENT,SALESM
AN,SALESMAN,SALESMAN,SALESMAN

这是您想要的,但您的 Oracle 数据库版本不支持它:

SQL> select listagg(distinct job, ',') within group (order by job) jobs from emp;
select listagg(distinct job, ',') within group (order by job) jobs from emp
       *
ERROR at line 1:
ORA-30482: DISTINCT option not allowed for this function

这是你应该做的:

SQL> select listagg(job, ',') within group (order by job) jobs
  2  from (select distinct job from emp);

JOBS
--------------------------------------------------------------------------------
ANALYST,CLERK,MANAGER,PRESIDENT,SALESMAN

SQL>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM