插入sql时递增

时间:2017-09-20 09:00:35

标签: sql-server postgresql

我有一张表格如下:

Department     Date          Budget
-----------------------------------
D1             2010-01-01      100
D2             2010-01-01      200
...             ...            ...

有没有办法编写一个自动增加特定部门的月份和预算的插入语句?

例如,我想为部门D1从1月到12月插入2010年的数据,每月增量为10。因此,结果表应如下所示

Department     Date          Budget
------------------------------------
D1             2010-01-01      100
D2             2010-01-01      200
D1             2010-02-01      110
D1             2010-03-01      120
D1             2010-04-01      130
...            ...             ...

我知道这可以通过一些脚本来实现,但是有没有办法通过insert和select语句实现这一点?

使用SQL Server(或)Postgres

3 个答案:

答案 0 :(得分:0)

对于Postgres:

insert into the_table (department, "date", budget)
select d.department, 
       d.date + interval '1 month' * row_number() over (order by g.i),
       d.budget + row_number() over (order by g.i)  * 10
from the_table d, generate_series(1,11) as g(i)
where d.department = 'D1';

这假设在运行此操作时,部门D1只存在一行

答案 1 :(得分:0)

尝试类似

的内容
insert into Table values
('D1',Dateadd(month,1,
(select top 1 Date from Table order by Date Desc)),budget)

答案 2 :(得分:0)

使用递归cte

;With cte(Department,[Date], Budget)
AS
(
SELECT 'D1','2010-01-01', 100 UNION ALL
SELECT 'D2','2010-01-01', 200
)
,cte2 AS 
( 
       SELECT 0 AS val , 
              0 AS val2 
       UNION ALL 
       SELECT val +1, 
              val2+10 
       FROM   cte2 
       WHERE  val<11 )
INSERT INTO the_table (department, [date], budget)    
SELECT department, 
           [date], 
           CASE 
                  WHEN rnk=0 THEN budget 
                  ELSE budget+val2 
           END AS Budget 
    FROM   ( 
                    SELECT   department, 
                             val2, 
                             Dateadd(month,val,[date])AS [Date], 
                             budget, 
                             Row_number()OVER(PArtition by Department ORDER BY [Date])-1 AS Rnk 
                    FROM     Cte2 , 
                             Cte )dt 
    WHERE  dt.department='D1'

结果

department    Date                  Budget
-------------------------------------------
D1          2010-01-01 00:00:00.000     100
D1          2010-02-01 00:00:00.000     110
D1          2010-03-01 00:00:00.000     120
D1          2010-04-01 00:00:00.000     130
D1          2010-05-01 00:00:00.000     140
D1          2010-06-01 00:00:00.000     150
D1          2010-07-01 00:00:00.000     160
D1          2010-08-01 00:00:00.000     170
D1          2010-09-01 00:00:00.000     180
D1          2010-10-01 00:00:00.000     190
D1          2010-11-01 00:00:00.000     200
D1          2010-12-01 00:00:00.000     210