拍攝日期'20130731'
,'20130805'
作爲示例的開始和結束日期,這個查詢將每天在這兩個日期之間返回您需要的數量。您可以更改真實查詢的參數。
;with cte as (
select d::date as d
from generate_series('20130731', '20130805', interval '1 day') as d
)
select
cte.d,
count(o.cohead_id) as cnt
from cte
left outer join cohead as o on
o.cohead_orderdate <= cte.d and
not exists (
select *
from comment as c
where
c.comment_date <= cte.d and
c.comment_text = 'Invoiced' and
c.comment_source_id = o.cohead_id
)
group by cte.d
order by cte.d
請參閱SQL FIDDLE EXAMPLE - 您可以添加/刪除行並檢查它是否正常工作。
希望有所幫助。
UPDATE: 如果你想獲得提交日期,而不是訂單日期,你不必來查詢訂單表都:
;with cte as (
select d::date as d
from generate_series('20130731', '20130805', interval '1 day') as d
), cte2 as (
select
c1.comment_date as submitted_date,
c2.comment_date as invoiced_date,
count(*) as cnt
from comment as c1
left outer join comment as c2 on
c2.comment_source_id = c1.comment_source_id and
c2.comment_text = 'Invoiced'
where c1.comment_text = 'Submitted'
group by c1.comment_date, c2.comment_date
)
select c1.d, sum(c2.cnt)
from cte as c1
left outer join cte2 as c2 on
c2.submitted_date <= c1.d and
(c2.invoiced_date is null or c2.invoiced_date > c1.d)
group by c1.d
order by c1.d
看到SQL FIDDLE與更新的查詢
更新2由於OP說他有查詢性能的問題,我試着用窗口函數編寫另一個。這個想法是獲取所有類型提交的日期計數減去發票類型的評論,然後獲得滾動總額。
;with cte1 as (
select d::date as d
from generate_series('20130731', '20130805', interval '1 day') as d
), cte2 as (
select
greatest('20130731', c.comment_date) as comment_date,
c.comment_text, count(*) as cnt
from comment as c
where
c.comment_text in ('Invoiced', 'Submitted') and
c.comment_date <= '20130805'
group by greatest('20130731', c.comment_date), c.comment_text
), cte3 as (
select
coalesce(cs.cnt, 0) - coalesce(ci.cnt, 0) as cnt,
coalesce(cs.comment_date, ci.comment_date) as comment_date
from (select * from cte2 where comment_text = 'Submitted') as cs
full outer join (select * from cte2 where comment_text = 'Invoiced') as ci on
cs.comment_date = ci.comment_date
)
select c1.d, sum(c3.cnt) over (order by c1.d)
from cte1 as c1
left outer join cte3 as c3 on c3.comment_date = c1.d
order by c1.d
SQL FIDDLE
。 。你能提供一些樣本數據和預期結果嗎? –