捕获二进制序列中最后一组1的第一个字符

时间:2017-06-19 15:13:04

标签: tsql

我有一个类似的系列:

Month   J F M A M J J A S O N D
Status  1 0 0 1 0 1 0 0 1 1 1 1

使用t-SQL,我试图捕获对应于最后一组1中第一个1的月份,即本例中的9月。

以下是我使用的代码:

IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL DROP TABLE #Temp1

    ;WITH PARTITIONED1 AS

    (SELECT         , t0.ID
            , t0.Year_Month
            , t0.Status
            , LAST_VALUE(t0.Year_Month) OVER (PARTITION BY t0.ID ORDER BY t0.Year_Month) AS D_YM
            , ROW_NUMBER() OVER (PARTITION BY t0.ID ORDER BY t0.Year_Month) AS rn1

    FROM #Temp0 t0

但是,这只会返回1的第一次出现;一月在这里。

我真的无法解决这个问题,所以任何帮助都会非常感激。

3 个答案:

答案 0 :(得分:1)

小心

  

虽然订购是在前一阶段进行的

之前的排序不保证以后的处理!

尝试这样的事情。这是一种非常简单的方法,您可以依赖无间隙ID:

DECLARE @tbl TABLE(ID INT IDENTITY,Mnth VARCHAR(100),[Status] TINYINT);
INSERT INTO @tbl VALUES
 ('J',1)
,('F',0) 
,('M',0) 
,('A',1) 
,('M',0) 
,('J',1) 
,('J',0) 
,('A',0) 
,('S',1) 
,('O',1) 
,('N',1) 
,('D',1);

SELECT a.*
FROM @tbl AS a
WHERE a.ID=(SELECT MAX(b.ID)+1 FROM @tbl AS b WHERE b.[Status]=0)

答案 1 :(得分:1)

这也可以使用:

select top 1 Month from table t where Status=1
and not exists
(select id from table t1 where stat=0 and t1.id>t.id)
order by t.id

答案 2 :(得分:1)

我可能过于复杂了,但不知道我把下面的表结构放在一起:

IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL DROP TABLE #Temp1
CREATE TABLE #Temp1
(
    Jan int,
    Feb int,
    Mar int,
    Apr int,
    May int,
    June int, 
    July int ,
    Aug int,
    Sep int,
    Oct int,
    Nov int,
    Dec int
)
insert into #temp1
select 
    1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1

IF OBJECT_ID('tempdb..#monthTranslate') IS NOT NULL DROP TABLE #monthTranslate
create table #monthTranslate
(
    MonthValue varchar(50), 
    MonthInt int
)
insert into  #monthTranslate
select 'Jan',1
union all select 'Feb',2 
union all select 'Mar',3
union all select 'Apr',4 
union all select 'May',5
union all select 'June',6
union all select 'July',7 
union all select 'Aug',8
union all select 'Sep',9 
union all select 'OCt',10 
union all select 'Nov',11
union all select 'Dec',12



--find the max month w\ 0 and add 1... becareful on null, it might return January incorrectly.  I'd check for that in a a case statement
select  max(b.MonthInt)+1
from  
(
    select
        MonthPassVal, months  , t.MonthInt  
    from 
    (
    select Jan, Feb, Mar, Apr, May, June, July, Aug, Sep, Oct, Nov, Dec
    from #temp1
    ) as r
    Unpivot
    (
        MonthPassVal for Months 
            in (Jan, Feb, Mar, Apr, May, June, July, Aug, Sep, Oct, Nov, Dec)
    ) as u
    inner join #monthTranslate t
        on t.MonthValue = months
)  as b 
where
    MonthPassVal=0