1

我有一个格式如下表的表格,我想将其拆分,以便有一个用于月份和年份的列,即。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 
4

2 回答 2

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 |
于 2013-02-14T21:47:53.287 回答
0

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

于 2013-02-14T21:44:33.163 回答