问题
I need to know how to select a row if the next row has a null value for specific column.
For example:
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
If Status is 'IE' and Option50 is NULL for the next record, then I need to return that next record. For the table above I need the query to find ind 47 and 53 and to return ind 48 and 54.
Ind | Opt50 | Stat
48 | NULL | NULL
54 | NULL | NULL
I am using SQL Server 2008. Any ideas?
回答1:
Assuming that the column Ind is a correlative, then:
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 with a demo of this.
And the results are:
╔═════╦════════╦════════╗
║ Ind ║ Opt50 ║ Stat ║
╠═════╬════════╬════════╣
║ 48 ║ (null) ║ (null) ║
║ 54 ║ (null) ║ (null) ║
╚═════╩════════╩════════╝
In the case that Ind has gaps in it, then you can do:
;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 with this version.
回答2:
Here you go! You can also use the PARTITION clause in the LEAD and LAG functions if you need. If this helps or you find it interesting, please up vote me so I can get lots of points so I can be cool! Peace Katherine
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];
来源:https://stackoverflow.com/questions/25693078/select-row-if-next-a-value-in-next-row-is-null