如果下一行的特定列具有空值,我需要知道如何选择行 例如:
Ind | Opt50 | Stat
44 | 1 | NR
45 | 1 | CL
46 | NULL | NULL
47 | 1 | IE
48 | NULL | NULL
49 | NULL | NULL
50 | 1 | NR
51 | 1 | IE
52 | 1 | CL
53 | 1 | IE
54 | NULL | NULL
如果Status为'IE'且Option50为下一条记录为NULL,那么我需要返回下一条记录。对于上表,我需要查询查找ind 47和53并返回ind 48和54.
Ind | Opt50 | Stat
48 | NULL | NULL
54 | NULL | NULL
我正在使用SQL Server 2008。 有任何想法吗?
答案 0 :(得分:4)
假设列Ind
是相关的,那么:
SELECT B.*
FROM dbo.YourTable A
INNER JOIN dbo.YourTable B
ON A.Ind = B.Ind - 1
WHERE A.Stat = 'IE'
AND B.Opt50 IS NULL
Here is a sqlfiddle,演示了这个。
结果是:
╔═════╦════════╦════════╗
║ Ind ║ Opt50 ║ Stat ║
╠═════╬════════╬════════╣
║ 48 ║ (null) ║ (null) ║
║ 54 ║ (null) ║ (null) ║
╚═════╩════════╩════════╝
如果Ind
中有空白,则可以执行以下操作:
;WITH CTE AS
(
SELECT *,
RN = ROW_NUMBER() OVER(ORDER BY Ind)
FROM dbo.YourTable
)
SELECT B.*
FROM CTE A
INNER JOIN CTE B
ON A.RN = B.RN - 1
WHERE A.Stat = 'IE'
AND B.Opt50 IS NULL
这个版本的Here is a sqlfiddle。
答案 1 :(得分:0)
你走了!如果需要,还可以在LEAD和LAG函数中使用PARTITION子句。如果这有帮助或者您觉得它很有趣,请向我投票,这样我就可以获得很多积分,这样我就可以变得很酷! 和平 兆
declare @table table (
[ind] [int]
, [opt50] [int]
, [stat] [nvarchar](25));
insert into @table
([ind],[opt50],[stat])
values (1,1,N'IE'),
(2,2,N'NotIE'),
(3,null,N'IE'),
(4,4,N'NotIE');
with [builder]
as (select [ind]
, [opt50]
, [stat]
, lag ([opt50]
, 1
, 0)
over (
order by [ind] asc) as [next_opt50]
from @table)
select [ind]
, [opt50]
, [stat]
, [next_opt50]
, case
when [opt50] is null
then
[next_opt50]
else
[opt50]
end as [what_i_really_want]
from [builder];