Oracle Query具有空值

时间:2015-10-15 10:01:14

标签: sql oracle

以下是要求,您能否帮助我获得所需的查询..

create table sales(Order_ID number, item varchar2(20));

insert into sales values (10, 'RICE');
insert into sales values (10, 'WATER');
insert into sales values (10, 'SALT');
insert into sales values (20, 'TOMATO');
insert into sales values (20, 'ONION');
insert into sales values (30, 'OIL');
insert into sales values (30, 'EGG');
insert into sales values (40, 'CHICKEN');
insert into sales values (50, 'FISH');

我需要输出格式如下。

Order_ID    ITEM
10          RICE
            WATER
            SALT
20          TOMATO
            ONION
30          OIL
            EGG
40          CHICKEN
50          FISH

4 个答案:

答案 0 :(得分:2)

使用row_number()分析函数加一个case语句,只填充第一行的order_id:

select case when rn = 1 then order_id end order_id,
       item
from   (select order_id,
               item,
               row_number() over (partition by order_id order by item) rn
        from   sales);

  ORDER_ID ITEM                
---------- --------------------
        10 RICE                
           SALT                
           WATER               
        20 ONION               
           TOMATO              
        30 EGG                 
           OIL                 
        40 CHICKEN             
        50 FISH      

答案 1 :(得分:2)

我通常在 SQL * Plus 中执行此操作,而这完全是关于格式化输出

您可以使用 BREAK ON column_name

例如,

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.

大多数基于GUI的客户端工具现在支持大多数 SQL*Plus命令。例如,在 SQL Developer 中,您可以作为脚本运行,即 F5 。在 PL / SQL Developer 中,SQL * Plus就像环境一样有一个不同的窗口。但是,如果你想要纯SQL方法,我建议@ Boneist的解决方案。

答案 2 :(得分:1)

使用以下查询来查找所需的o / p

select case when rno=1
    then 
    order_id
    else
    null
    end
    as order_id,item
    from
    (
    select order_id,item, row_number() over (partition by order_id order by order_id)  rno from sales
    )

答案 3 :(得分:1)

使用LAG(COLUMN_NAME)OVER(ORDER BY)

LAG(COLUMN_NAME)获得了之前的记录。

SELECT DECODE(ORDER_ID, PRE_ORDER_ID, null, ORDER_ID) AS ORDER_ID,
       ITEM
  FROM
    (SELECT ORDER_ID,
            LAG(ORDER_ID) over 
                (order by ORDER_ID) AS PRE_ORDER_ID,
            ITEM
       FROM SALES);