SQL查询 - 规范化

时间:2018-03-23 10:58:57

标签: sql oracle

我想有选择地将单个月份列(1月,2月,3月)转换为单个新列作为Month。我应该使用哪些SQL查询来执行此操作?

输入:

Item   |Measure |Jan |Feb  |Mar  |Apr  |May  |Jun  |Jul  |Aug  |Sep  |Oct  |Nov  |Dec |
---------------------------------------------------------------------------------------
110053 | sales  |559 |1738 |755  |769  |519  |919  |519  |709  |779  |589  |519  |699 |
110053 | gm     |333 |790  |452  |457  |309  |547  |309  |422  |459  |350  |309  |416 |
110053 | cost   |56  |234  |75   |77   |52   |92   |52   |71   |79   |59   |52   |70  |
---------------------------------------------------------------------------------------

输出

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要unpivot条款:

destroy_tree(LP)
destroy_tree(LP->p[0])
delete LC1->prev 
delete LC1
destroy_tree(LP->p[1]) // but at this point LP is already deleted
delete LC2->prev // but at this point LP is already deleted
delete LC2
delete LP->prev // at his point LP is already deleted 
delete LP  // at this point LP is already deleted

答案 1 :(得分:0)

以下是您的问题的解决方案:

select Item,Month,sales,gm,cost 
from (
        select Item,Measure,Month,sales,
        CASE Month 
             WHEN 'JAN' Then 1
             WHEN 'FEB' THEN 2 
             WHEN 'MAR' THEN 3 
             WHEN 'APR' THEN 4 
             WHEN 'MAY' THEN 5 
             WHEN 'JUN' THEN 6 
             WHEN 'JUL' THEN 7 
             WHEN 'AUG' THEN 8 
             WHEN 'SEP' THEN 9 
             WHEN 'OCT' THEN 10 
             WHEN 'NOV' THEN 11 
             WHEN 'DEC' THEN 12
         ELSE 0
         END Month_num
   FROM (select Item,Measure,Month,sales
      from Table1
      unpivot
      (
        sales
        for Month in (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
       )
    )
)
pivot 
(
   sum(sales)
   for Measure in ('sales' AS Sales,'gm' AS gm,'cost' AS cost)
)
ORDER BY Month_num

要了解有关下面链接的透视和非透视使用的更多信息:

  

http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html

演示请点击链接:

  

http://sqlfiddle.com/#!4/9b4e2/25