【问题标题】:Getting the last number of a time period and displaying it in another column获取时间段的最后一个数字并将其显示在另一列中
【发布时间】:2017-08-04 00:29:06
【问题描述】:

我正在尝试获取一天中某个时间段的最后一个数字并将其显示在另一列中,直到日期发生变化。以下是我现在拥有的数据示例。

DT                          no_of_records
2017-05-01 00:00:00.000     241
2017-05-01 04:00:00.000     842
2017-05-01 08:00:00.000     1049
2017-05-01 12:00:00.000     1517 
2017-05-01 16:00:00.000     1627
2017-05-01 20:00:00.000     2077
2017-05-02 00:00:00.000     151
2017-05-02 04:00:00.000     772
2017-05-02 08:00:00.000     951
2017-05-02 12:00:00.000     1114
2017-05-02 16:00:00.000     1693
2017-05-02 20:00:00.000     1992

下面是我想要的输出。

DT                          no_of_records   total
2017-05-01 00:00:00.000     241             2077
2017-05-01 04:00:00.000     842             2077
2017-05-01 08:00:00.000     1049            2077
2017-05-01 12:00:00.000     1517            2077
2017-05-01 16:00:00.000     1627            2077
2017-05-01 20:00:00.000     2077            2077
2017-05-02 00:00:00.000     151             1992
2017-05-02 04:00:00.000     772             1992
2017-05-02 08:00:00.000     951             1992
2017-05-02 12:00:00.000     1114            1992
2017-05-02 16:00:00.000     1693            1992
2017-05-02 20:00:00.000     1992            1992

您对如何获取总列有任何想法吗?

【问题讨论】:

标签: sql sql-server


【解决方案1】:

您可以使用first_value窗口函数。

select dt,no_of_records
,first_value(no_of_records) over(partition by cast(dt as date) order by dt desc) as toal
from tbl

【讨论】:

    【解决方案2】:

    或者,您可以尝试执行子查询:

    select dt, no_of_records, total = (select max(no_of_records) from table1
                                      where convert(date,dt) = convert(date,t1.dt))
    from table1 as t1
    

    【讨论】:

      【解决方案3】:

      使用 CTE 查询。您可能需要将连接运算符的日期转换为整数。

      with cte_SumPerday
      (
      DateOfDay,
      TotalPerDay
      )
      as
      (
      select
       cast(dt as date) as DateOfDay,
       max(no_of_records) as TotalPerDay
       group by
       cast(dt as date)
      from transactions
      )
      ,
      cte_TransactionsAndDays
      (
       dt,
       nr_of_records,
       DateOfDay
      )
      as
      (
      select
       *,
       cast(DT as date) as DateOfDay
      from transactions
      )
      
      select
      *
      from cte_TransactionsAndDays T
      join cte_SumPerday S on
       S.DayofDate = T.DayOfDate
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多