PIVOT Oracle - 将多行数据转换为具有多列的单行,不包含聚合数据

时间:2015-06-18 17:47:37

标签: sql oracle oracle11g pivot

我需要传输以下数据集:

enter image description here

其中只有突出显示的行是感兴趣的行(Tag in('LN','SN')),因为我只对产品的SerialNumber和LotNumber感兴趣。 我想将上面的数据集转换为以下数据集: enter image description here

它列出产品及其序列号和批号在一行中。

在线阅读之后,我认为PIVOT可能就是我需要的。但是,我正在努力处理声明的技术方面。

我试过了:

well

但这不会产生我想要的输出。有什么建议吗? PIVOT是正确使用的语句还是在这种情况下是否有其他更合适的陈述?我意识到PIVOT需要一个聚合函数,但我不计算或添加任何东西。请指教。

下面是我的测试表及其数据

select * from (
select * from TEST2 where tag in ('LN','SN')
)
PIVOT
(
  max(value)
  for tag in ('LN','SN')
)
order by category,subcat,item,"Date"

2 个答案:

答案 0 :(得分:3)

您没有对描述做任何事情,这也随着标记而变化。它没有被聚合,所以它在隐含的'组中,因此您在结果集中获得了单独的行。

您也可以使用其他(虚拟)聚合来捕获它:

select * from (
  select * from TEST2 where tag in ('LN', 'SN')
)
PIVOT
(
  max(value) as value, max(description) as description
  for tag in ('LN' as ln, 'SN' as sn)
)
order by category, subcat, item, "Date";

Date      SUBCAT CATEGOR IT LN_VALUE          LN_DESCRIPTION  SN_VALUE          SN_DESCRIPTION
--------- ------ ------- -- ----------------- --------------- ----------------- ---------------
24-OCT-13 290223 1219576 25 1105618           Lot Number      3x12mm            Serial Number  
24-OCT-13 290223 1219576 28 1303757           Lot Number                                       
18-JUN-15 354506 1219576 4  1403114           Lot Number                                       
18-JUN-15 354506 1219576 9  7777777777        Lot Number      9.999999999999E12 Serial Number  

或者更有可能通过指定您想要的列而不是使用*将其从中间结果集中排除(如果您不想要它):

select * from (
  select category, subcat, item, "Date", tag, value
  from TEST2 where tag in ('LN', 'SN')
)
PIVOT
(
  max(value) for tag in ('LN' as ln, 'SN' as sn)
)
order by category, subcat, item, "Date";

CATEGOR SUBCAT IT Date      LN                SN              
------- ------ -- --------- ----------------- -----------------
1219576 290223 25 24-OCT-13 1105618           3x12mm           
1219576 290223 28 24-OCT-13 1303757                            
1219576 354506 4  18-JUN-15 1403114                            
1219576 354506 9  18-JUN-15 7777777777        9.999999999999E12

答案 1 :(得分:0)

在数据透视表xml中获取表数据


with a as (select to_char(xmltype.getclobval(JOB_XML))  k  from (
select * from (select ename,job from emp)

pivot xml ( max(ename) for job in (select job from emp))))

SELECT EXTRACTVALUE(VALUE(xml_list), '//column[1]') AS interface_no
      ,EXTRACTVALUE(VALUE(xml_list), '//column[2]') AS interface_name_a
  FROM TABLE(XMLSEQUENCE(EXTRACT(XMLType('<?xml version="1.0" encoding="UTF-8"?>'||(select * from a) ), 'PivotSet/item'))) xml_list;

相关问题