I have the following structure in my Oracle database:
Date Allocation id
2015-01-01 Same 200
2015-01-02 Good 200
2015-01-03 Same 200
2015-01-04 Same 200
2015-01-05 Same 200
2015-01-06 Good 200
I would like to have a query that has to check for only the previous consecutive days and get the count where Allocation is "Same"
.
I want to select by a date, for example 2015-01-05
.
Example output: for the date 2015-01-05
the count is 3
.
New problem. With the query from Lukas Eder the count is always 1
or 2
. but the expected is 3
. Why?!
Date Allocation id
2015-01-01 Same 400
2015-01-02 Good 400
2015-01-03 Same 400
2015-01-04 Same 400
2015-01-05 Same 400
2015-01-06 Good 400
Code from Lukas Eder
SELECT c
FROM (
SELECT allocation, d, count(*) OVER (PARTITION BY allocation, part ORDER BY d) AS c
FROM (
SELECT allocation, d,
d - row_number() OVER (PARTITION BY allocation ORDER BY d) AS part
FROM t
)
)
WHERE d = DATE '2015-01-05';
The expected output is something like this, First_day end Last day not necessary:
id count first_day Last_Day
200 3 2015-01-03 2015-01-05
400 3 2015-01-03 2015-01-05
This query will yield the counts for each row:
You can then filter on it to find the counts for a given row:
Explanation:
The derived table is used to calculate different "partitions"
part
for each date and allocation:The result is:
The concrete date produced by
part
is irrelevant. It's just some date that will be the same for each "group" of dates within an allocation. You can then count the number of identical values of(allocation, part)
using thecount(*) over(...)
window function:to produce your wanted result.
Data
I've used the following table for the example: