加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – Max()Over Partition By with date conditions

发布时间:2020-12-12 08:54:24 所属栏目:MsSql教程 来源:网络整理
导读:如何将以下结果变为黄色? 我想找到上一年的最高分(不包括当前日期)和Name1和Parent1的分区 我已经尝试了以下没有给出所需结果的内容,它只返回正确分区的max,但是在所有日期之间. select [VDate],[Name1],[Parent1],[Score],max(case when [VDate] dateadd(ye
如何将以下结果变为黄色?

我想找到上一年的最高分(不包括当前日期)和Name1和Parent1的分区

我已经尝试了以下没有给出所需结果的内容,它只返回正确分区的max,但是在所有日期之间.

select 
[VDate],[Name1],[Parent1],[Score],max(case when [VDate] > dateadd(year,-1,[VDate]) then [Score] else null end) over (partition by [Name1],[Parent1]) AS MaxScoreInPreviousLast12Months
from [dbo].[Control]

表数据:

CREATE TABLE Control
    ([VDate] datetime,[Name1] varchar(10),[Parent1] varchar(10),[Score] int);

INSERT INTO Control ([VDate],[Score])
VALUES
('2018-08-01 00:00:00','Name1','Parent1',80),('2018-07-01 00:00:00',85),('2018-06-01 00:00:00',90),('2017-09-01 00:00:00',100),('2017-08-01 00:00:00',95),('2017-07-01 00:00:00',70),('2018-08-01 00:00:00','Name2','Parent2',('2017-10-01 00:00:00',60),'Name3','Parent3',96),99),105)
;

这适用于SQL Server 2016

解决方法

这是一种使用外部应用于相关子查询的方法.感谢您发布ddl和示例数据.使这很好,易于使用.
select c.*,x.MaxScore
from Control c
outer apply
(
    select MaxScore = max(Score)
    from Control c2
    where c2.VDate < c.VDate
        and c2.VDate >= dateadd(year,c.VDate)
        and c.Name1 = c2.Name1
        and c.Parent1 = c2.Parent1
) x

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读