【问题标题】:How to avoid duplicated values in a column in sql如何避免sql中列中的重复值
【发布时间】:2020-09-12 03:39:02
【问题描述】:

我正在使用下面的代码从两个表中获取数据。但我可以在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

请提出建议。

【问题讨论】:

  • 你使用的是哪个数据库,oracle/sql server/mysql等
  • 我正在使用 oracle
  • @GeorgeJoseph “PL/SQL(过程语言/结构化查询语言)是 Oracle Corporation 的 SQL 过程语言扩展。”

标签: sql oracle window-functions


【解决方案1】:

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

否则,首先从表中选择 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>

【讨论】:

  • 我试过 listagg (distinct) 它不起作用。我的意思是我收到错误 ORA-30482: DISTINCT option not allowed for this function 30482. 00000 - "DISTINCT option not allowed for this function"
  • 我正在使用 Oracle 数据库。
  • 正如我所说,最近 Oracle 数据库版本 (19c) 支持它。您使用哪个版本?如果较低,则无法正常工作,因此您必须应用我在第二段中的建议。
  • 我加了一个例子;请看一下。
  • 好的。正如我所说:STRINGAGG 或 STRINGAGG_DISTINCT 不是标准的 Oracle 函数。那是您的数据库中存在的东西。无论如何,我很高兴你成功了。感谢您告知我们。
猜你喜欢
  • 2017-03-03
  • 2019-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
相关资源
最近更新 更多