结合创建的表和Listagg查询

时间:2018-06-28 14:56:28

标签: sql oracle listagg

当前,我有两部分代码,一个用于创建表,另一个用于对表进行列表处理。代码看起来像这样:

Create table NewTable nologging as
select  distinct x as customerNumber,
y as items bought,
z as prices
from 
    customerNum,
    numItems,
    itemPrice
where  (z not in ('2.00','3.00','NA'))

,然后是紧随其后的Listagg

create table formattingSection nologging as
select newTable.customerNumber, listagg(newTable.bought,',') within group (order 
by bought) as boughtdesc
from newTable
group by customerNumber

是否可以将这两部分合并为一个部分?这样我就没有2张桌子了?

1 个答案:

答案 0 :(得分:0)

我想是这样的

create table formattingSection nologging as
select 
  customerNumber, 
  listagg(bought, ',') within group (order by bought) as boughtdesc
from 
  -- instead of "newTable" itself, use SELECT statement from "CREATE TABLE newTable"
  (select distinct x as customerNumber,
                   y as items bought,
                   z as prices
   from 
     customerNum,
     numItems,
     itemPrice
   where (z not in ('2.00', '3.00', 'NA'))
     -- and ... --> you should join those tables, somehow. Otherwise, Cartesian product 
     -- will be created, and that's probably not what you want. 
  )
group by customerNumber;

除了我在代码中编写的注释之外,“ z”列似乎代表“价格”,并且似乎将其存储在VARCHAR2列中。我建议你不要这样做。使用NUMBER数据类型。为什么?因为没有什么阻止您将价格输入为“ x。%i”或“ 2 =&3”。如果这样的决定是由于“ NA”而引起的,那么没问题-您只需将其保留为 empty ,其值为NULL。为了显示目的,您可以DECODE这样的值:decode(z, null, 'NA', z)