aggregate value in different rows

▼魔方 西西 提交于 2019-12-23 04:58:09

问题


i have data like this table

ItemId  Value   Date
1        2      2017-12-18 17:00:00.000
1        2      2017-12-18 17:02:00.000
1        2      2017-12-18 17:04:00.000
1        3      2017-12-18 17:06:00.000
1        3      2017-12-18 17:08:00.000
1        2      2017-12-20 17:10:00.000
1        2      2017-12-20 17:12:00.000

i want to output like this in sql server

ItemId     Value   MaxDate

1          2       2017-12-18 17:04:00.000
1          3       2017-12-18 17:08:00.000
1          2       2017-12-20 17:12:00.000

I'm sorry, I did not get a better sentence for my title


回答1:


This can be done with a difference of row numbers approach. Look at the results of the inner query that classifies consectuive rows with the same value into one group which can be used to get the final result.

select itemid,value,max(date)
from (
select t.*,
row_number() over(partition by itemid order by date)
-row_number() over(partition by itemid,value order by date) as grp
from tbl t
) t
group by itemid,value,grp

Edit: Just getting the min or max would be easier with Gordon's answer. However, if both min, max and sum and other aggregations are needed per group, this version would be better.




回答2:


You want the rows where the next row has a different value:

select t.*
from (select t.*,
             lead(value) over (partition by itemid order by date) as next_value
      from t
     ) t
where next_value is null or next_value <> value;



回答3:


Not sure if you are trying to do a basic aggregation where you want the max datetime value for each day or you are trying to do an islands and gaps problem where the group is defined because the "previous" row changes value. But I think you just need basic aggregation.

Here is a fully working example which return the output you stated you want.

declare @Something table
(
    ItemId int
    , Value int
    , [Date] datetime
)
insert @Something values
(1, 2, '2017-12-18 17:00:00.000')
, (1, 2, '2017-12-18 17:02:00.000')
, (1, 2, '2017-12-18 17:04:00.000')
, (1, 3, '2017-12-18 17:06:00.000')
, (1, 3, '2017-12-18 17:08:00.000')
, (1, 2, '2017-12-20 17:10:00.000')
, (1, 2, '2017-12-20 17:12:00.000')

select ItemId
    , Value
    , MaxDate = Max([Date])
from @Something
group by ItemId
    , Value
    , convert(Date, [Date])
order by MAX([Date])


来源:https://stackoverflow.com/questions/47872427/aggregate-value-in-different-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!