根据条件及其在给定日期的前几行操作列检索最新行

问题描述 投票:1回答:1

数据集:

IF OBJECT_ID('tempdb..#temp') IS NOT NULL
    DROP TABLE #temp

CREATE TABLE #temp(
user_id [int]  NOT NULL,
date [datetime] NOT NULL,
fieldid [int] NOT NULL,
fieldvalue NVARCHAR(100) NOT NULL,
fromvalue [int] NULL,
tovalue [int]  NULL,
action char(1) NOT NULL,
audit_date [datetime] NOT  NULL
)

Insert into #temp values ( 1,'2020-01-01',1,'a',NULL,0,'C','2020-01-01 21:00:39.000 ');

Insert into #temp values ( 2,'2020-01-01',1,'a',NULL,0,'C','2020-01-01 21:00:39.000 ');
Insert into #temp values ( 2,'2020-01-01',1,'a',NULL,0,'N','2020-01-01 22:00:39.000 ');

Insert into #temp values ( 2,'2020-01-01',1,'b',NULL,0,'C','2020-01-01 21:00:39.000 ');
Insert into #temp values ( 2,'2020-05-05',1,'a',NULL,0,'C','2020-05-05 21:00:39.000 ');
Insert into #temp values ( 2,'2020-05-05',2,'a',NULL,0,'C','2020-05-05 21:00:39.000 ');
Insert into #temp values ( 2,'2020-05-05',1,'b',NULL,0,'C','2020-05-05 21:00:39.000 ');
Insert into #temp values ( 2,'2020-05-05',3,'c',NULL,0,'C','2020-05-05 21:00:39.000 ');

Insert into #temp values ( 3,'2020-01-02',1,'a',NULL,0,'C','2020-01-01 10:00:39.000 ');
Insert into #temp values ( 3,'2020-01-02',1,'a',NULL,0,'N','2020-01-01 11:00:39.000 ');
Insert into #temp values ( 3,'2020-01-02',1,'a',NULL,0,'C','2020-01-01 12:00:39.000 ');

Insert into #temp values ( 4,'2020-10-10',1,'a',NULL,0,'C','2020-01-01 22:00:39.000 ');
Insert into #temp values ( 4,'2020-10-10',1,'a',1   ,0,'U','2020-01-01 23:00:39.000 ');`

条件 对于给定的用户ID,日期,字段ID,给定日期的字段值,当fromvalue = 0且tovalue = 1且操作<>'N'时仅包含最新行

sql查询

with cte as
(
    select user_id, date, fieldid, fieldvalue, fromvalue, tovalue
        , action, audit_date
        ,  ROW_NUMBER() OVER(PARTITION BY user_id, date, fieldid, fieldvalue ORDER BY audit_date desc) AS 'rnk'
    from #temp (nolock)  
)
select * from cte where rnk = 1 and action <>'N'  and fromvalue IS NULL and  tovalue = 0 ;

我认为现在已经获得了此查询。到目前为止,请进行检查。

注:根据有效评论编辑了原始帖子。我对此并不陌生,以后我将发布DTD。

数据集:IF OBJECT_ID('tempdb ..#temp')不为空删除表#temp创建表#temp(user_id [int]非为空,日期为[datetime]非为空,fieldid [int]非为空,字段值为NVARCHAR (100)不是...

sql sql-server tsql greatest-n-per-group window-functions
1个回答
0
投票

您使用row_number()的尝试就在那儿,但是需要将整个过滤逻辑移到计算窗口函数的子查询中。否则,可能会首先对不符合条件的行进行排名,然后在外部查询中将其排除。

© www.soinside.com 2019 - 2024. All rights reserved.