获取最后一个时间段的数字并将其显示在另一列中

时间:2017-08-03 15:23:09

标签: sql sql-server

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

let a = [10,15,20];
let b = a.push(20);

console.log('a = ', a);
console.log('b = ', b);

以下是我想要的输出。

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

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

3 个答案:

答案 0 :(得分:2)

您可以使用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

答案 1 :(得分:0)

使用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

答案 2 :(得分:0)

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

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