2

我对 SQL 很陌生,并试图解决这个问题:

我有一个名为 BUDGET 的表,该表在一年中的每个月都有 12 列,显示该月的预算余额。所以表格看起来像这样:

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

我想要做的是规范化这个表并将每一行分成 12 行,每一行都有一个以下格式的日期字段。我还想要一个显示当月值的 [Balance] 列。因此,标准化表将如下所示:

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

我尝试在同一张表上使用 CROSS JOIN 但失败了。我也尝试使用 while 循环,但也失败了。任何形式的帮助表示赞赏。谢谢!

编辑:我正在使用 SQL Server 2008

4

3 回答 3

10

只是为了好玩,这里有一个 CROSS APPLY 解决方案:

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。

如果您必须将日期作为字符串,则将字符串放入 CROSS APPLY 中,然后将('01', Month1)SELECT 更改为Convert(char(4), B.Year) + M.Mo.

于 2012-08-07T01:29:07.090 回答
4
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];
于 2012-08-07T01:10:56.483 回答
1

我就是这样做的。没必要全神贯注。

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.
于 2012-08-07T01:22:14.733 回答