【问题标题】:Unpivot Table SQL Oracle反透视表 SQL Oracle
【发布时间】:2016-06-06 17:16:29
【问题描述】:

我已经阅读了一些帖子,但无法提出解决方案。

我有以下答案表。 ID 184 将有未知数量的条目,因此不能对每个数量和名称进行硬编码。

ID TEXT TAG ORD 184 Halifax Bnk 1 184 RBS Bnk 2 184 Natwest Bnk 3 184 32.16 Amt 1 184 80.15 Amt 2 184 62.54 Amt 3

我需要基于 TAG 和 ORD 的以下输出我需要列出银行和金额。

Bank Amount Halifax 32.16 RBS 80.15 Natwest 62.54

到目前为止我的代码......

select *  
from 
(select
f.id as "ID"
,a.text as "01TEXT"
,a.tag as  "02TAG"
,a.ord as "03ORD"
from
freq f

left join answers a
on a.freq_id = f.id and a.tag in ('Bnk','Amt')

where
f.id = 184
)unpivot (amount for tag in ("03ORD"))

任何帮助将不胜感激。 谢谢 根兹

【问题讨论】:

    标签: sql oracle oracle11g unpivot


    【解决方案1】:

    您不需要UNPIVOT 该数据。你需要PIVOT它。这将为您提供所需的结果:

    with test_data as (
    SELECT 184 ID,     'Halifax' text,   'Bnk' tag,     1 ord from dual union all
    SELECT 184 ID,     'RBS' text,   'Bnk' tag,     2 ord from dual union all
    SELECT 184 ID,     'Natwest' text,   'Bnk' tag,     3 ord from dual union all
    SELECT 184 ID,     '32.16' text,   'Amt' tag,     1 ord from dual union all
    SELECT 184 ID,     '80.15' text,   'Amt' tag,     2 ord from dual union all
    SELECT 184 ID,     '62.54' text,   'Amt' tag,     3 ord from dual
    )
    select bank_name, amount from test_data
    pivot ( max(text) for tag in ('Bnk' as bank_name, 'Amt' as amount) )
    order by ord
    

    您只对最后 3 行感兴趣。 test_data SQL 只是提供一个工作示例,而无需访问您的表。

    【讨论】:

    • 您阅读我的回复了吗?我“硬编码”了test_data 中的条目,以便为我提供查询数据。它们不是解决方案的一部分。实际的解决方案只对tag 字段中的值进行硬编码。
    • 谢谢你,马修。这行得通,我现在需要解决 TEXT 列的 LONG 数据类型。
    【解决方案2】:

    这是另一种方式

    select
    
    f.text  as "Bank"
    ,a.text as "Amount"
    from  answers f
    left join answers a
    on a.id = f.id 
    and a.tag ='Amt'
    and a.ord = f.ord
    
    where
    f.id = 184
    and f.tag = 'Bnk'
    

    【讨论】:

      猜你喜欢
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多