基于月份将一行拆分为多行

时间:2013-02-14 21:38:14

标签: sql sql-server unpivot

我有一个格式如下所示的表格,我想将它拆分,所以这是一个月和年的列,即。 2014年1月然后另一栏费用。所以有效地将每一行分成12个不同的行,但我不知道我的生活如何处理它。任何帮助将不胜感激

    CREATE TABLE dbo.Line14(
    ItemID int IDENTITY(1,1) NOT NULL,
    Detail nvarchar(max) NULL,
    Type nvarchar(255) NULL,
    Cat nvarchar(255) NULL,
    Jan_14 money NULL,
    Feb_14 money NULL,
    Mar_14 money NULL,
    Apr_14 money NULL,
    May_14 money NULL,
    Jun_14 money NULL,
    Jul_14 money NULL,
    Aug_14 money NULL,
    Sep_14 money NULL,
    Oct_14 money NULL,
    Nov_14 money NULL,
    Dec_14 money NULL
) ON PRIMARY TEXTIMAGE_ON PRIMARY
GO 

2 个答案:

答案 0 :(得分:3)

您应该能够使用UNPIVOT函数将数据从列转换为行:

select itemid,
  detail,
  type,
  cat,
  Month,
  2014 as Year,
  value
from Line14
unpivot
(
  value
  for Month in (Jan_14, Feb_14, Mar_14, Apr_14,
                May_14, Jun_14, Jul_14, Aug_14,
                Sep_14, Oct_14, Nov_14, Dec_14)
) unpiv

请参阅SQL Fiddle with Demo

结果与此类似:

| ITEMID | DETAIL | TYPE |  CAT |  MONTH | YEAR | VALUE |
---------------------------------------------------------
|      1 |   Test |    C | blah | Jan_14 | 2014 |    10 |
|      1 |   Test |    C | blah | Feb_14 | 2014 |    12 |
|      1 |   Test |    C | blah | Mar_14 | 2014 |    45 |
|      1 |   Test |    C | blah | Apr_14 | 2014 |    56 |
|      1 |   Test |    C | blah | May_14 | 2014 |    89 |
|      1 |   Test |    C | blah | Jun_14 | 2014 |    78 |
|      1 |   Test |    C | blah | Jul_14 | 2014 |    96 |
|      1 |   Test |    C | blah | Aug_14 | 2014 |    35 |
|      1 |   Test |    C | blah | Sep_14 | 2014 |    55 |
|      1 |   Test |    C | blah | Oct_14 | 2014 |    30 |
|      1 |   Test |    C | blah | Nov_14 | 2014 |    99 |
|      1 |   Test |    C | blah | Dec_14 | 2014 |   120 |

答案 1 :(得分:0)

按照你的描述构建新表 - 然后编写12个insert as select语句,获取每个月的货币价值并硬编码月份值。