T-SQL渐进式编号分区

时间:2017-09-11 10:14:28

标签: sql-server tsql sql-server-2012 partitioning ranking

我的目标是获得像这样的记录集

date   flag   number
01     0      1
02     0      1
03     1      2
04     1      2
05     1      2
06     0      3
07     1      4
08     1      4

我从" date"的记录集开始和" flag"只要。我正在尝试计算"数字"列使用T-SQL排名和分区功能。

正常排名会产生如下结果:

 date   flag   number
    01     0      1
    02     0      1
    03     1      2
    04     1      2
    05     1      2
    06     0      1
    07     1      2
    08     1      2

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

你可以试试这个:

IEnumerable<Node>

enter image description here

我们的想法是使用Items函数检查组的更改时间:

TreeView

然后,使用DECLARE @DataSource TABLE ( [date] CHAR(2) ,[flag] BIT ); INSERT INTO @DataSource ([date], [flag]) VALUES ('01', 0) ,('02', 0) ,('03', 1) ,('04', 1) ,('05', 1) ,('06', 0) ,('07', 1) ,('08', 1); WITH DataSource ([date], [flag], [number]) AS ( SELECT [date] ,[flag] ,IIF(LAG([flag], 1, NULL) OVER (ORDER BY [date]) = [flag], 0, 1) FROM @DataSource ) SELECT [date] ,[flag] ,SUM([number]) OVER (ORDER BY [date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS [number] FROM DataSource ORDER BY [date], [flag]; LAG组进行更改。

答案 1 :(得分:1)

Ĵ,

SQL Server 2012有许多新功能,例如SQL Lead()和SQL Lag()函数。您可以使用SQL Server Lag() function来解决您的要求

这是我的解决方案

with cte as (
select 
    date, flag, 
    LAG(flag, 1, NULL) OVER (ORDER BY date) AS preVal,
    case when flag = ISNULL( ( LAG(flag, 1, NULL) OVER (ORDER BY date) ), flag) then 0 else 1 end as i
from recordset
)
select
    cte.date,
    cte.flag,
    sum(cte2.i)+1 r
from cte
inner join cte as cte2 on cte.date >= cte2.date
group by cte.date, cte.flag
order by cte.date

答案 2 :(得分:0)

您可以在这样的游标中填充它:

DECLARE  @Table TABLE (
[Date] [nvarchar](50) NULL,
[flag] [int] NULL,
[Number] [int] NULL
) 

DECLARE @Date nvarchar(50)
DECLARE @flag int
DECLARE @number int
DECLARE @flagnumber int
DECLARE @flagincrement int

DECLARE  MyCursor CURSOR FOR
SELECT [Date],FLag
FROM [LegOgSpass].[dbo].[testflag]
Order by [Date]

OPEN MyCursor
FETCH NEXT FROM MyCursor
INTO @Date,@flag

IF (@@FETCH_STATUS>=0)
BEGIN

SET @number = 1
SET @flagincrement = @flag

INSERT INTO @Table ([Date],[Flag],[Number])
VALUES(@Date,@flag,@number)

FETCH NEXT FROM MyCursor INTO @Date,@flag
END
WHILE (@@FETCH_STATUS<>-1)
BEGIN
IF (@@FETCH_STATUS<>-2)
IF @flagincrement = @flag 
SET @number = @number 

ELSE
SET @number = @number+1
SET @flagincrement = @flag

INSERT INTO @Table ([Date],[Flag],[Number])
VALUES(@Date,@flag,@number)
FETCH NEXT FROM MyCursor INTO @Date,@flag
END

CLOSE MyCursor
DEALLOCATE MyCursor

SELECT * FROM @Table