我的Oracle数据库中有以下结构:
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
我希望有一个查询只需检查前几天的连续日,并获得分配为"Same"
的计数。
我想按日期选择,例如2015-01-05
示例输出:对于日期2015-01-05
,计数为3
。
新问题。根据Lukas Eder的查询,计数始终为1
或2
。但预期的是3
。从2015-01-03到2015-01-05。
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
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';
答案 0 :(得分:0)
您可以使用不同的行来标识组。这就是你的查询正在做的事情。如果您想要特定日期的值,请使用:
select t.*
from (select t.*,
(row_number() over (order by date) -
row_number() over (partition by allocation order by date)
) as grp
from table t
) t
where d = date '2015-01-05';
我最好猜测为什么问题中的版本不起作用是因为您的date
可能有时间组件。我假设d
是date
列。
编辑:
要获取计数,请使用子查询和count(*)
作为分析函数:
select t.*
from (select t.*, count(*) over (partition by grp, allocation) as cnt
from (select t.*,
(row_number() over (order by date) -
row_number() over (partition by allocation order by date)
) as grp
from table t
) t
) t
where d = date '2015-01-05';
或者,如果您只想要计数,则可以使用聚合:
select date, count(*) as cnt
from (select t.*,
(row_number() over (order by date) -
row_number() over (partition by allocation order by date)
) as grp
from table t
) t
group by date, allocation
having date = date '2015-01-05';
答案 1 :(得分:0)
给它一个旋转:
create table mbtmp(d_date date, alloc varchar2(20), id number);
insert into mbtmp values (to_date('2015-01-01','yyyy-mm-dd'),'SAME',200);
insert into mbtmp values (to_date('2015-01-02','yyyy-mm-dd'),'GOOD',200);
insert into mbtmp values (to_date('2015-01-03','yyyy-mm-dd'),'SAME',200);
insert into mbtmp values (to_date('2015-01-04','yyyy-mm-dd'),'SAME',200);
insert into mbtmp values (to_date('2015-01-05','yyyy-mm-dd'),'SAME',200);
insert into mbtmp values (to_date('2015-01-06','yyyy-mm-dd'),'GOOD',200);
COMMIT;
SELECT max(length(sames) - length(replace(sames,'|',null)) - 1) from (
select regexp_substr( pth,'[|SAME]+') sames
FROM(
SELECT sys_connect_by_path(alloc,'|') pth
from mbtmp m
WHERE d_Date > ( select max(d_date) from mbtmp
where d_Date < to_date('2015-01-05','yyyy-mm-dd')
And alloc != 'SAME' )
START WITH d_Date = to_date('2015-01-05','yyyy-mm-dd')
CONNECT BY Prior d_date = d_date + 1));
现在,如果不是连续日规则,即 - 如果即使日期列表中存在间隙仍然可以计算,那么您可以使用更简单的查询:
select count(d_Date)
FROM mbtmp
WHERE d_Date > ( select max(d_date) from mbtmp
where d_Date < to_date('2015-01-05','yyyy-mm-dd')
And alloc != 'SAME' )
and d_date <= to_date('2015-01-05','yyyy-mm-dd')