假设有一个Oracle表,其中包含empty
列
------------------
| empty | count |
| true | 0 |
| true | 0 |
| false | 1 |
| true | 0 |
| false | 2 |
| true | 0 |
| false | 3 |
| false | 4 |
| true | 0 |
| false | 5 |
| ............. |
------------------
所需的查询应返回数据empty
列以及上面的count
列,该列应记录empty
列不为空的累积行数,且结果不应受影响通过order by
条款
此外,如何改进查询以显示结果如下表结果集?基本上让empty==true
列保留前一个empty==false
列的计数
------------------
| empty | count |
| true | 0 |
| true | 0 |
| false | 1 |
| true | 1 |
| false | 2 |
| true | 2 |
| false | 3 |
| false | 4 |
| true | 4 |
| true | 4 |
| true | 4 |
| false | 5 |
| ............. |
------------------
在此处更新第二个问题的查询
WITH dates_list AS
(SELECT TO_DATE('01-31-2018','MM-dd-yyyy') + ROWNUM - 1 AS DAY
FROM dual
CONNECT BY LEVEL <= (TO_DATE('03-31-2018','MM-dd-yyyy') - TO_DATE('01-31-2018','MM-dd-yyyy')+1)
)
select all_date, week_date, count(case when flag is not null then 1 end)
over (partition by flag order by week_date) as cnt
from (
SELECT dates1.day as all_date, dates2.day as week_date, case when dates2.day is null then 0 else 1 end as flag
FROM dates_list dates1
LEFT JOIN
(SELECT *
FROM dates_list
WHERE TO_CHAR(DAY,'D') NOT IN (7,1)
) dates2 ON dates1.day = dates2.day
)
order by all_date;
此线程中的示例表是上表中的一个简单模拟,基本上我尝试得到所有非周末日期的索引,但是任何周末日期都应该保留前一个非周末索引(如果没有则为0)
答案 0 :(得分:2)
您的第二个请求比第一个请求简单。你没有改善&#34;第一个问题的解决方案,你写了一个不同的(和更简单的)查询。
假设排序是由另一列ord
(可能是数字,日期或其他):
select empty,
count(case empty when 'false' then 1 end) over (order by ord) as cnt
from .....
答案 1 :(得分:1)
如果你想要&#34;假&#34;要枚举的列(以及其他值为0),则需要一个指定排序的列。 SQL表表示无序集,因此您需要一个指定排序的列。为方便起见,我打电话给id
:
select t.*,
(case when empty = 'false' then row_number() over (partition by empty order by id)
else 0
end) as count
from t;