Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何遍历表_Sql_Sql Server_Sql Server 2008 - Fatal编程技术网

Sql 如何遍历表

Sql 如何遍历表,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,嗨, 很抱歉,这可能是一个愚蠢的问题,但我真的需要一些帮助。 所以我想创建上面的输出。前两列是输入id和日期。逻辑是使用14天和21天作为截止日期,通过比较当前记录和上次保存的记录的日期来决定是否将记录保存在同一id内。每个id的第一条记录始终保留标志为1表示保留,0表示其他 例如,对于id 1,如果截止日期为21,则第二条记录的日期为2013年1月16日,比上一条记录(即2013年1月1日的第一条记录)晚15天,15如果我们讨论的是基于日期对数据进行排序,就像在您的示例中,我们可以使用类似于以

嗨, 很抱歉,这可能是一个愚蠢的问题,但我真的需要一些帮助。 所以我想创建上面的输出。前两列是输入id和日期。逻辑是使用14天和21天作为截止日期,通过比较当前记录和上次保存的记录的日期来决定是否将记录保存在同一id内。每个id的第一条记录始终保留标志为1表示保留,0表示其他


例如,对于id 1,如果截止日期为21,则第二条记录的日期为2013年1月16日,比上一条记录(即2013年1月1日的第一条记录)晚15天,15如果我们讨论的是基于日期对数据进行排序,就像在您的示例中,我们可以使用类似于以下代码说明的内容,我只使用YourID和YourDate字段:

ID  Date    flag_14  flag_21
1   1/1/2013    1     1
1   1/16/2013   1     0
1   1/19/2013   0     0
1   1/23/2013   0     1
1   1/26/2013   0     0
2   1/1/2013    1     1    
2   1/18/2013   1     0
从那里,您可以比较从r到r1的日期,并更新/插入所需内容

更新:我知道它在2012年起作用,但它有滞后和超前,2008 R2,不确定它在2005年或以下运行。

请尝试它,它按照问题工作


哪个版本的SQL Server?这可以在2012年更容易地解决,因为它已经实现了新的分析函数LAG、LEAD等。不幸的是,我有2008版…这没有生成OP想要的flag14和flag21列。谢谢!!但我不仅要和前一天比较。我需要与上次保存的记录的日期进行比较,因此需要再增加一层…我正在与该层进行斗争。。。
CREATE TABLE SeData(
    YourID INT,
    YourDate DATE
)

INSERT INTO SeData
VALUES (1,'2013-01-01')
 , (1,'2013-01-16')
 , (1,'2013-01-19')
 , (1,'2013-01-23')
 , (1,'2013-01-26')

;WITH Roll AS(
    SELECT ROW_NUMBER() OVER (ORDER BY YourDate) ID
        , YourID
        , YourDate
    FROM SeData
)
SELECT *
    , (DAY(r1.YourDate) - DAY(r.YourDate)) AS NumberBetween -- just an example of comparing
FROM Roll r
    INNER JOIN Roll r1 ON r.ID = (r1.ID - 1)
with cte as
(
select o.*
from( 
    select  yourid,yourdate,ROW_NUMBER () Over (partition by yourid order by (select(0)) ) as RN
    from sedata 
    ) as o 
),
cte2 as
(
select r.*,
    case when  r.RN %2=0
    then
    (select DAY(r.YourDate) - DAY(r1.YourDate) where r.yourid = r1.yourid) 
    else
   (select DAY( r.YourDate) - DAY(min(YourDate)) from sedata where r.yourid = r1.yourid )
    end as Total   


 from cte r left  join cte r1 ON r.RN-1 = r1.RN  
 )
 select *
  ,case when   Total is null then 1 when Total >14 and Total <21 then 1   else 0  end as flag_14 ,
   case when  Total is null then 1 when Total > 21 then 1   else 0  end  as flag_21

  from cte2   where Total is not null or RN=1