如何从单列创建多个行 - 规范化的表(How to create multiple rows fro

2019-09-20 22:37发布

我是相当新的SQL,并试图找出了这一点:

我有一个表叫预算有一年的每个月12列,显示该月的预算平衡。 因此,表看起来像这样:

[Department]  [Year]  [Month1] [Month2] .... [Month12]  
ABCD           2010   $5000     $5500   .....  $4000
ABCD           2011   $6000     $6500   .....  $3000

我所试图做的是规范这个表,打破每一行到12行,每行用以下格式的日期字段。 我也希望有一个[平衡]列显示该月的值。 因此,标准化的表如下所示:

[Department]  [Date]     [Balance] 
ABCD          20100101     $5000   
ABCD          20100201     $5500 
ABCD          20100301     .....
ABCD          .......      ......

我试着用CROSS在同一个表连接,但失败了。 我用while循环也试过,但失败也是如此。 任何形式的帮助表示赞赏。 谢谢!

编辑:我使用SQL Server 2008

Answer 1:

只是为了好玩这里的CROSS应用的解决方案:

SELECT
   B.Department,
   DateAdd(month, (B.Year - 1900) * 12 + M.Mo - 1, 0) [Date],
   M.Balance
FROM
   dbo.Budget B
   CROSS APPLY (
      VALUES
      (1, Month1), (2, Month2), (3, Month3), (4, Month4), (5, Month5), (6, Month6),
      (7, Month7), (8, Month8), (9, Month9), (10, Month10), (11, Month11), (12, Month12)
   ) M (Mo, Balance);

它比@Aaron Bertrand的UNPIVOT真的没有什么不同,不使用UNPIVOT。

如果你必须有日期作为字符串,然后把在横线APPLY像('01', Month1)和改变选择要Convert(char(4), B.Year) + M.Mo



Answer 2:

SELECT 
  Department, 
  [Date] = DATEADD(MONTH, CONVERT(INT, SUBSTRING([Month],6,2))-1, 
     DATEADD(YEAR, [Year]-1900, 0)), 
  Balance
FROM
  dbo.BUDGET AS b
  UNPIVOT 
  (
    Balance FOR [Month] IN 
    (
      Month1, Month2,  Month3,  Month4,
      Month5, Month6,  Month7,  Month8,
      Month9, Month10, Month11, Month12
    )
  ) AS y
ORDER BY Department, [Date];


Answer 3:

这就是我要做的事。 没有必要让所有的幻想了。

select department = b.department ,
       year       = b.year       ,
       month      = m.month      ,
       balance    = case m.month
                    when  1 then b.Month1
                    when  2 then b.Month2
                    when  3 then b.Month3
                    when  4 then b.Month4
                    when  5 then b.Month5
                    when  6 then b.Month6
                    when  7 then b.Month7
                    when  8 then b.Month8
                    when  9 then b.Month9
                    when 10 then b.Month10
                    when 11 then b.Month11
                    when 12 then b.Month12
                    else         null
                    end
from dbo.budget b
join (           select month =  1
       union all select month =  2
       union all select month =  3
       union all select month =  4
       union all select month =  5
       union all select month =  6
       union all select month =  7
       union all select month =  8
       union all select month =  9
       union all select month = 10
       union all select month = 11
       union all select month = 12
     ) m on 1 = 1  -- a dummy join: we want the cartesian product here so as to expand every row in budget into twelve, one per month of the year.


文章来源: How to create multiple rows from a single row - normalize a table