Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting all rows until first occurrence of given value

Tags:

sql

oracle

For following data:

date|value|check
2009 | 5 | 1
2008 | 5 | 1
2007 | 5 | 1
2006 | 5 | 0
2005 | 5 | 0
2004 | 5 | 1
2003 | 5 | 1
2002 | 5 | 1

I need to select all rows from 2009 back until first occurrence of 0 in check column:

date|value|check
2009 | 5 | 1
2008 | 5 | 1
2007 | 5 | 1

I tried with the lag function, but I was only able to check a month back.

I am working on Oracle 10g.

UPDATE:

All seems to work well, my test data set is too small to say anything about the performance differences.

like image 460
Kamil Zadora Avatar asked Apr 09 '09 12:04

Kamil Zadora


People also ask

How do I SELECT all rows to except the first row in SQL?

The SQL EXCEPT operator is used to return all rows in the first SELECT statement that are not returned by the second SELECT statement. Each SELECT statement will define a dataset. The EXCEPT operator will retrieve all records from the first dataset and then remove from the results all records from the second dataset.

How do I SELECT all rows except one?

Select the header or the first row of your list and press Shift + Ctrl + ↓(the drop down button), then the list has been selected except the first row.

How do I SELECT a certain number of rows?

Select one or more rows and columns Or click on any cell in the column and then press Ctrl + Space. Select the row number to select the entire row. Or click on any cell in the row and then press Shift + Space. To select non-adjacent rows or columns, hold Ctrl and select the row or column numbers.

What is the difference between SELECT * and SELECT 1?

There is no difference between EXISTS with SELECT * and SELECT 1. SQL Server generates similar execution plans in both scenarios.


2 Answers

SELECT * FROM mytable where date > (
   SELECT max(date) FROM mytable where check = 0    
) 
like image 133
kenj0418 Avatar answered Oct 13 '22 14:10

kenj0418


SELECT  *
FROM    (
        SELECT  m.*,
                MIN(CASE WHEN check = 0 THEN 0 ELSE 1 END) OVER (ORDER BY date DESC)) AS mn
        FROM    mytable
        )
WHERE   mn = 1

or even better:

SELECT  *
FROM    (
        SELECT  m.*, ROW_NUMBER() OVER (ORDER BY mydate DESC) AS rn
        FROM    mytable m
        ORDER BY
                mydate DESC
        )
WHERE   rownum = DECODE(check, 0, NULL, rn)
ORDER BY
        mydate DESC

The latter query will actually stop scanning as soon as it encounters the first zero in check.

like image 32
Quassnoi Avatar answered Oct 13 '22 15:10

Quassnoi