【问题标题】:How to foreach check data and display horizontally?如何foreach检查数据并水平显示?
【发布时间】:2016-09-26 08:55:33
【问题描述】:

以下是我的数据样本集:

ID    DATETIME    
1     29-12-2016 03:00
2     28-12-2016 14:00
3     28-12-2016 16:00
4     25-12-2016 00:00

预期结果:

ID    DATETIME             24HoursDataExisted
1     29-12-2016 03:00     0
2     28-12-2016 14:00     1
3     28-12-2016 16:00     1
4     25-12-2016 00:00     0

如何编写这样的查询,每条记录在接下来的 24 小时内是否存在另一条记录?它与DATEADD(hh, 24,datetime) 有关,但我不确定如何将其写成 SQL。
从上面的样本数据来看,ID2记录为真,因为ID1和ID3的记录,ID3为真,因为ID1记录。

【问题讨论】:

    标签: sql sql-server sql-server-2008


    【解决方案1】:

    如果你使用的是2012,你可以使用lead函数..

    select id,datetimee,
    case  
    when datediff(hour,convert(datetime,datetimee,105),cast(lead(convert(datetime,datetimee,105)) 
    over (order by convert(datetime,datetimee,105)) as datetime))<=24 
    then 1 else 0 end
    from #temp
    order by id desc
    

    2008年,你可以在下面使用

    ;with cte
    as
    (
    select id,convert(datetime,datetimee,105) as dtval,
    row_number() over (order by id desc) as rownum
    from #temp
    )
    select c1.id,c1.dtval,
    case when datediff(hour,c1.dtval,c2.dtval)<=25 then 1 else 0 end as comecol
     from cte c1
    left join cte c2
    on c1.rownum+1=c2.rownum
    

    输出:

    id  datetimee          somecol
    4   25-12-2016 00:00    0
    3   28-12-2016 16:00    1
    2   28-12-2016 14:00    1
    1   29-12-2016 15:00    0
    

    【讨论】:

    • 你能解释一下datetimee的来源吗?
    • 感谢您的回复,但应用程序仍在 SQL server 2008 上运行
    • @Twinkles:这是一些基于用户数据的虚拟列
    猜你喜欢
    • 2021-01-07
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多