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.
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.
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.
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.
There is no difference between EXISTS with SELECT * and SELECT 1. SQL Server generates similar execution plans in both scenarios.
SELECT * FROM mytable where date > (
SELECT max(date) FROM mytable where check = 0
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With