【问题标题】:pivot table with two rows into columns具有两行到列的数据透视表
【发布时间】:2020-04-08 05:59:33
【问题描述】:

我的表有下一个结果:

our_date | number_people
------------------------
23/09/19 |  26
24/09/19 |  26

总是只有两行

我想旋转这个结果并得到这个:

our_date_1   | number_people_1   | our_date_2   | number_people_2
-----------------------------------------------------------------
23/09/19     |  26               | 24/09/19     |   26

获取 number_people_1 和 number_people_2 之间的差异

我尝试:

select *
from table_1
pivot(
    count(number_people)
    for our_date in (:P_TODAY, :P_YESTERDAY)
)

这是我的实际错误:

ORA-56900: la variable de enlace no está soportada en la operación PIVOT|UNPIVOT
56900. 0000 -  "bind variable is not supported inside pivot|unpivot operation"
*Cause:    Attempted to use bind variables inside pivot|unpivot operation.
*Action:   This is not supported.

怎么了?如何在 for 子句中使用动态值?

最好的问候

【问题讨论】:

    标签: sql oracle pivot


    【解决方案1】:

    错误表明:

    for fecha in (our_date)
    

    不能将our_date(列名)作为值列表;它(list)必须包含常量,例如

    for our_date in (date '2019-09-23', date '2019-09-24')
    

    修复该问题后,查询可能如下所示:

    SQL> with table_1 (our_date, number_people) as
      2    (select date '2019-09-23', 26 from dual union all
      3     select date '2019-09-24', 26 from dual
      4    )
      5  select *
      6  from table_1
      7  pivot (max(number_people)
      8         for our_date in (date '2019-09-23', date '2019-09-24')
      9        );
    
    TO_DATE(' 2019-09-23 00:00:00' TO_DATE(' 2019-09-24 00:00:00'
    ------------------------------ ------------------------------
                                26                             26
    
    SQL>
    

    但是,这并不是你想要的。

    如果该表中有 3、4 或更多行怎么办?有可能吗,还是总是只有 2 行?


    如果总是只有 2 行,self-join 可以完成这项工作。例如:

    SQL> with table_1 (our_date, number_people) as
      2    (select date '2019-09-23', 26 from dual union all
      3     select date '2019-09-24', 22 from dual
      4    ),
      5  temp as
      6    (select our_date, number_people,
      7       row_number() over (order by our_date) rn
      8     from table_1
      9    )
     10  select
     11    a.our_date our_date_1,
     12    a.number_people number_people_1,
     13    --
     14    b.our_date our_date_2,
     15    b.number_people number_people_2
     16  from temp a cross join temp b
     17  where a.rn = 1
     18    and b.rn = 2;
    
    OUR_DATE_1 NUMBER_PEOPLE_1 OUR_DATE_2 NUMBER_PEOPLE_2
    ---------- --------------- ---------- ---------------
    23.09.2019              26 24.09.2019              22
    
    SQL>
    

    【讨论】:

    • 我的问题是:里面的值不能是静态值。那些必须是动态的,我更新我的查询
    • 总是两行
    • 那么好;我修改了答案并添加了更多代码。请看一下。
    • 完美,非常感谢@Littlefoot
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    相关资源
    最近更新 更多