对于SQL查询/存储过程,我希望找到给定值在一段时间内按类型的峰值之和。此外,如果峰值在给定的时间段内没有下降趋势,则不应将其计算在内。
数据,例如:
类型 | 金额 | 日期 | |
---|---|---|---|
AAA | 10 | 2021-07-11 | |
AAA | 15 | 2021-07-11 | |
AAA | 20 | 2021-07-11 | |
AAA | 25 | 2021-07-11*需要这个峰值 | |
AAA | 20 | 2021-07-11 | |
AAA | 15 | 2021-07-11 | |
AAA | 10 | 2021-07-11 | |
AAA | 15 | 2021-07-11 | |
AAA | 20 | 2021-07-11 | |
AAA | 25 | 2021-07-11 | |
AAA | 30 | 2021-07-11*需要将此峰值添加到前一峰值 | |
AAA | 20 | 2021-07-11 | |
AAA | 15 | 2021-07-11 | |
AAA | 10 | 2021-07-11 | |
血脑屏障 | 10 | 2021-07-11 | |
血脑屏障 | 20 | 2021-07-11 | |
血脑屏障 | 30 | 2021-07-11*需要这个峰值 | |
血脑屏障 | 20 | 2021-07-11 | |
血脑屏障 | 10 | 2021-07-11 | |
CCC | 10 | <2021-07-11>||
CCC | 20 | 2021-07-11 | |
CCC | 30 | 2021-07-11 | |
CCC | 20 | 2021-07-11 | |
CCC | 10 | <2021-07-11>||
CCC | 20 | 2021-07-11 | |
CCC | 30 | 2021-07-11 | |
CCC | 40 | 2021-07-11*此峰值不计算在内,因为下降趋势发生在第二天 | |
CCC | 30 | 2021-07-12 | |
CCC | 20 | 2021-07-12 | |
CCC | 10 | <2021-07-12>
让我假设您的date
列有一个时间组件。您实际上需要对行进行显式排序,而日期是不够的。
如果是,则可以使用lead()
和lag()
:
select t.*
from (select t.*,
lag(amount) over (partition by type, convert(date, date) order by date) as prev_amount,
lead(amount) over (partition by type, convert(date, date) order by date) as next_amount
from t
) t
where prev_amount < amount and amount > next_amount;
编辑:
对于最终协议:
select type, sum(amount)
from (select t.*,
lag(amount) over (partition by type, convert(date, date) order by date) as prev_amount,
lead(amount) over (partition by type, convert(date, date) order by date) as next_amount
from t
) t
where prev_amount < amount and amount > next_amount;
group by type;
给定当前的表结构,这是不可能的。您至少需要另外一列来指示每条记录的顺序。否则,查询不能保证
AAA 10 2021-07-11
总是在之前
AAA 15 2021-07-11
并没有迹象表明为什么第二个比第一个晚。