Get rid from one column duplicate values in two column select

╄→尐↘猪︶ㄣ 提交于 2019-11-28 11:37:14

问题


So, I`ve got two columns t1.NAME and t2.ITEMS, for each neme there can be more than one item assigned to it, so I want to select it like:

| NAME | ITEMS |
  JOHN    1
          2
  BEN     4
          7
          3
  DAVE    5

P.s. if it helps, they are connected by t1.id = t2.names_id


回答1:


Result of my below query is very close to what you want.. the only difference is, there is no blank name, because you cannot directly do that result in one step query.. each item belong to name of each id in t1. BUT you can do some trick there if you want to get the exact result, you can use UPDATE to do some trick with the result.

    SELECT t1.NAME, t2.ITEMS
    FROM t1 INNER JOIN t2 ON t1.id = t2.names_id



回答2:


This kind of operation should be done in presentation layer.

But if you insist you can use sth like:

SqlFiddleDemo

SELECT DISTINCT NAME,
      LISTAGG(Items,  chr(13)||chr(10)) WITHIN GROUP (ORDER BY 1) OVER (PARTITION BY Name) AS Items
FROM tab

change tab with subquery that produce output you get now.

The clue is to concatenate for every name corresponding Items and adding new line character CHR(13) + CHR(10).




回答3:


I usually do it in SQL*Plus and it is all about formatting your output.

You could use BREAK ON column_name.

For example,

SQL> break on deptno
SQL> SELECT deptno, ename FROM emp order by deptno;

    DEPTNO ENAME
---------- ----------
        10 CLARK
           KING
           MILLER
        20 JONES
           FORD
           ADAMS
           SMITH
           SCOTT
        30 WARD
           TURNER
           ALLEN
           JAMES
           BLAKE
           MARTIN

14 rows selected.


来源:https://stackoverflow.com/questions/32882516/get-rid-from-one-column-duplicate-values-in-two-column-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!