我有一张包含以下记录的表格:
Id Partitioned SDDate
1 1 2014-01-01
2 2 2014-01-02
3 3 2014-01-03
4 4 2014-01-04
5 5 2014-01-05
6 6 2014-01-06
7 7 2014-01-07
8 1 2014-01-08
9 2 2014-01-09
10 3 2014-01-10
11 4 2014-01-11
12 5 2014-01-12
13 6 2014-01-13
14 7 2014-01-14
15 1 2014-01-15
16 2 2014-01-16
正如您所看到的,记录是从1-7分区的,我想要实现的是将该组的记录插入临时表。 达到最大分区ID数时,再次启动插入。 感谢。
我正在使用SQL SERVER 2008 RC2
这是代码:
Set NoCount On;
--
Declare
@InputTable As DT_HorasExtras
--
Insert Into @InputTable
( HorasExtra, Fecha )
Values
(3, '2014-01-01'),
(3, '2014-01-02'),
(1, '2014-01-03'),
(2, '2014-01-03'),
(1, '2014-01-05'),
(3, '2014-01-06'),
(3, '2014-01-07'),
(3, '2014-01-08'),
(3, '2014-01-09'),
(3, '2014-01-10'),
(3, '2014-01-11'),
(3, '2014-01-12'),
(3, '2014-01-13'),
(3, '2014-01-14'),
(3, '2014-01-15'),
(3, '2014-01-16')
Declare @Idx Int = 1, @InnerIncrementor Int = 1;
--
Declare
--
@PartitionedId Int,
@Fecha Date,
@HorasExtra Int,
@Id Int;
--
DECLARE IDs CURSOR LOCAL FOR
Select
t.Id
From utilsFilterAndPartitionHorasExtras(@InputTable) t
OPEN IDs
FETCH NEXT FROM IDs into @Id
WHILE @@FETCH_STATUS = 0
BEGIN
--
Select
@HorasExtra = t.HorasExtra,
@Fecha = t.Fecha,
@PartitionedId = t.Partitioned
From utilsFilterAndPartitionHorasExtras(@InputTable) t
Where t.Id = @Id
--
print 'Particion Dia: ' + Convert(varchar(max), @PartitionedId) + ', Fecha: ' + Convert(varchar(max), @Fecha) + ', Horas extras: ' + Convert(varchar(max), @HorasExtra);
--*** HERE I WANT TO INSERT RECORDS ONLY FROM PARTITION 1 TO 7
--*** WHEN 7 IS REACHED START INSERT AGAIN
insert into #tmpTable values(@Field1,.,,
-- inc
Set @Idx+=1;
FETCH NEXT FROM IDs into @Id
END
CLOSE IDs
DEALLOCATE IDs
这是输出:
Particion Dia: 1, Fecha: 2014-01-01, Horas extras: 3
Particion Dia: 2, Fecha: 2014-01-02, Horas extras: 3
Particion Dia: 3, Fecha: 2014-01-03, Horas extras: 3
Particion Dia: 4, Fecha: 2014-01-05, Horas extras: 1
Particion Dia: 5, Fecha: 2014-01-06, Horas extras: 3
Particion Dia: 6, Fecha: 2014-01-07, Horas extras: 3
Particion Dia: 7, Fecha: 2014-01-08, Horas extras: 3
Particion Dia: 1, Fecha: 2014-01-09, Horas extras: 3
Particion Dia: 2, Fecha: 2014-01-10, Horas extras: 3
Particion Dia: 3, Fecha: 2014-01-11, Horas extras: 3
Particion Dia: 4, Fecha: 2014-01-12, Horas extras: 3
Particion Dia: 5, Fecha: 2014-01-13, Horas extras: 3
Particion Dia: 6, Fecha: 2014-01-14, Horas extras: 3
Particion Dia: 7, Fecha: 2014-01-15, Horas extras: 3
Particion Dia: 1, Fecha: 2014-01-16, Horas extras: 3
答案 0 :(得分:0)
如果要为这些行分配组ID,则可以从id中减去分区:
select (partition - id) as grp, t.*
from table t
如果id
值确实不一定是连续的,您可以将row_number()
用于此目的:
select (row_number() over () order by (id, partition) - id) as grp, t.*
from table t
这将识别每个组。我不确定你插入它们并重新开始是什么意思。