SQL查询-值不能与上一行相同

时间:2018-11-06 20:17:44

标签: sql-server tsql

我正在尝试根据商品编号和交易类型返回一些数据。我只想查看每种交易类型的最新日期。如何使给定项目编号的rn 1中的交易类型不等于给定项目编号的rn 2中的交易类型。

SELECT 
    *
FROM 
    (SELECT  
         [ItemN], 
         [TransacDate], 
         [TransacType],
         ROW_NUMBER() OVER(PARTITION BY [ItemN] ORDER BY [ItemN] ASC) rn
     FROM 
         [Huxley].[dbo].[FGInvDetail]
     WHERE
         ([TransacType] = 1 OR [TransacType] = 3)) a
WHERE 
    rn = 1 OR rn = 2

查询结果

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试将transactype添加到分区中,并按transacdate DESC排序。最后,您只想保留rn = 1

   SELECT * FROM (
                SELECT  [ItemN], 
                        [TransacDate], 
                        [TransacType],
                        ROW_NUMBER() OVER(PARTITION BY [ItemN], [transactype] ORDER BY [transacdate] Desc) rn
                    FROM [Huxley].[dbo].[FGInvDetail]
                    where ([TransacType] = 1 or [TransacType] = 3)
              ) a
WHERE rn = 1