使用sql更改表

时间:2014-07-30 23:13:17

标签: mysql sql sql-server tsql

我有这张桌子

**Original Table**          
year    month   duration    amount per month
2012    5       3           2000

我希望得到这个

**Result table**            
year    month   duration    amount per month
2012    5       1           2000
2012    6       1           2000
2012    7       1           2000

请注意项目的持续时间(这是一个项目)是3,“每月的金额”是2000,所以我又添加了两行,以显示下个月(6和7)将有“金额”每个月“也是如此。我怎么用sql / tsql做到这一点?

3 个答案:

答案 0 :(得分:1)

尝试使用SQL SERVER,我包含了我的测试临时表:

declare @temp as table
(
 [year] int
, [month] int
, [duration] int
, [amount] int
)
insert into @temp
( 
 [year] 
, [month] 
, [duration] 
, [amount]
)
VALUES(
 2012
,5
,3
,2000
)

SELECT
 [year] 
,[month] + n.number
,1
,[amount]
,   '1' + SUBSTRING(CAST([duration] AS varchar(10)), 2, 1000) AS Items
FROM @temp
JOIN master..spt_values n
    ON n.type = 'P'
    AND n.number < CONVERT(int, [duration])

答案 1 :(得分:1)

请参阅下面可能符合您要求的脚本。我还补偿了日历年和月的增量。请测试并告诉我。

DECLARE @temp AS TABLE([Year] INT,[Month] INT,Duration INT,Amount INT)

INSERT INTO @temp([year], [month], Duration, Amount)
VALUES (2011, 5, 3, 2000),(2012, 11, 3, 3000),(2013, 9, 12, 1000);

;WITH cte_datefix
    AS (
    SELECT [Year],
         [Month],
         Duration,
         Amount,
         CAST(CAST([Year] AS VARCHAR(4)) + RIGHT('00' + CAST([Month] AS VARCHAR(2)), 2) + '01' AS DATE) AS [Date]
    FROM @temp
    ),
cte_Reslut
    AS (SELECT [Year],
            [Month],
            Duration,
            Amount,
            [Date],
            1 AS Months
       FROM cte_datefix
       UNION ALL
       SELECT t.[Year],
            t.[Month],
            t.Duration,
            t.Amount,
            DATEADD(M, Months, t.[Date]) AS [Date],
            cr.Months + 1 AS Months
       FROM cte_Reslut AS cr
           INNER JOIN cte_datefix AS t
           ON t.[Year] = cr.[Year]
       WHERE cr.Months < cr.Duration
    )
    SELECT YEAR([Date]) AS [Year],
         MONTH([Date]) AS [Month],
         1 AS Duration,
         Amount
    FROM cte_Reslut
    ORDER BY [Date]

答案 2 :(得分:0)

对于那些想知道如何根据需要增加年份的人,这里有一个基于Suing响应的例子(非常简单,只包括两个案例陈述):

select
 2012 as [year] 
,11 as [month]
,5 as [duration]
,2000 as [amount]
into #temp

select * from #temp

SELECT
 case 
    when [month] + n.number > 12 
        then [year] + 1 
        else [year]
    end as [year] 
,case 
    when [month] + n.number > 12 
        then [month] + n.number - 12 
        else [month] + n.number 
    end as newYear
,1 as newDuration
,[amount]
,   '1' + SUBSTRING(CAST([duration] AS varchar(10)), 2, 1000) AS Items
FROM #temp
JOIN master..spt_values n
    ON n.type = 'P'
    AND n.number < CONVERT(int, [duration])

drop table #temp