如何从Oracle SQL中的表取消透视

时间:2019-06-03 12:25:04

标签: oracle oracle11g oracle12c

我有1-5个渐进式折扣板。这些板可能因一项交易而异。我想将所有五个值存储在5个变量中。

我的桌子是这样的。

enter image description here

期望值是这样

enter image description here

示例:2

如果我的桌子是这样的

enter image description here

期望值是这样

enter image description here

示例:3

如果我的桌子是这样的

enter image description here

期望值是这样

enter image description here

也只能有一个或两个平板。

预先感谢

1 个答案:

答案 0 :(得分:1)

这是一个多列枢轴,而不是不可枢轴:

--BUILD Sample dataset called MyTable 
WITH MyTable as (
SELECT 0 slab_from, 100 slab_to, 1 discount FROM dual union all
SELECT 100 slab_from, 200 slab_to, 5 discount FROM dual union all
SELECT 200 slab_from, 99999999 slab_to, 8 discount FROM dual ),

--Now build a CTE with a row number that we can use to pivot the data.
CTE as (SELECT Slab_from, Discount, row_number() over (Order by slab_FROM) RN 
     FROM myTable)

--Now build the data set.  Though I'm a bit confused why there are 4 slabs and 3 discounts in your expected results...

SELECT * FROM (SELECT * FROM CTE)
PIVOT (
max(slab_from) as SLAB, max(Discount) as Discount --[We could add max(Slab_to) SLABTO] to get the max value for each as well if needed...
for RN in (1,2,3,4,5)  --RowNumber values 1-5 since 5 is max according to question
);

上面提供了我们:

+--------+------------+--------+------------+--------+------------+--------+------------+--------+------------+
| 1_SLAB | 1_DISCOUNT | 2_SLAB | 2_DISCOUNT | 3_SLAB | 3_DISCOUNT | 4_SLAB | 4_DISCOUNT | 5_SLAB | 5_DISCOUNT |
+--------+------------+--------+------------+--------+------------+--------+------------+--------+------------+
|      0 |          1 |    100 |          5 |    200 |          8 |        |            |        |            |
+--------+------------+--------+------------+--------+------------+--------+------------+--------+------------+

如果您希望列名以0开头,则只需从CTE中的RN减去1。

可能的答案2:Tweeked:假设所有平板范围都从0开始,并且1-5保留用于可能/可能不在基表中的实际行。

--BUILD Sample dataset called MyTable 
WITH MyTable as (
SELECT 0 slab_from, 100 slab_to, 1 discount FROM dual union all
SELECT 100 slab_from, 200 slab_to, 5 discount FROM dual union all
SELECT 200 slab_from, 99999999 slab_to, 8 discount FROM dual),

--Now build a CTE with a row number that we can use to pivot the data.
CTE as (SELECT 0 "0_SLAB", Slab_to, Discount, row_number() over (Order by slab_FROM) RN 
     FROM myTable)

--Now build the data set.  Though I'm a bit confused why there are 4 slabs and 3 discounts in your expected results...

SELECT * FROM (SELECT * FROM CTE)
PIVOT (
max(slab_to) as SLAB, max(Discount) as Discount --[We could add max(Slab_to) SLABTO] to get the max value for each as well if needed...
for RN in (1,2,3,4,5)  --RowNumber values 1-5 since 5 is max according to question
);

这里唯一的区别是我使用slab_to并将0_SLAB硬编码为0,因此所有其他可能的范围都从1-5调整。

列是前缀而不是后缀,但这就是数据透视表的方式。并且它们并不是按所有平板的顺序排列,其次是所有折扣;但是又这就是枢轴的工作方式;但是只要数据正确且可重复,列顺序和名称就不会重要。

但是我仍然在为为什么需要枢轴而苦苦挣扎。您在标准化的基于行的表中拥有了所需的数据,虽然在应用程序中提取了需要迭代的数据并提出了它,但我不知道为什么我们需要数据进行透视。