2017-04-04 76 views
0

我試圖通過按星期編號顯示sql查詢,並顯示星期周結束而不是星期開始,但迄今爲止已無濟於事實現。我怎樣才能做到這一點?按星期編號和星期結尾

select extract(week from actual_sale_date) as week_number, 
to_char(date_trunc('week', actual_sale_date) as date, 'MM/dd/yyyy'), count(*) 
from data 
where project_id = 'ABC' 
and actual_sale_date >= date_trunc('year',current_date) 
group by rollup((actual_sale_date)) 

結果:

week_number  date     count 
    1    01/02/2017    2 
    1    01/02/2017    1      
    2    01/09/2017    1 
    2    01/09/2017    1 
    2    01/09/2017    1 
    3    01/16/2017    3 
    3    01/16/2017    1 
              10 

要求:

week_number     week_ending      count 
    1      01/08/2017      3 
    2      01/15/2017      3 
    3      01/22/2017      4 
                   10 
+2

嘗試'+'1周'::間隔 - '1天'::間隔'?.. –

+0

感謝您照顧周結束問題。 –

+0

@JakeWagner是的,在'to_char()'裏面 - 你也不會在'GROUP BY'中使用'date_trunc()',所以你在一週內得到多個結果。 - 你需要像'GROUP BY date_trunc('week',actual_sale_date),提取(從actual_sale_date一週)' – pozs

回答

1

你被actual_sale_date因此一個星期,結果並沒有獲得通過每週彙總分組。要獲取星期結束日期,請在星期開始時添加6天。在rollup中使用week_number和周結束日期。

select extract(week from actual_sale_date) as week_number, 
to_char(date_trunc('week', actual_sale_date) + interval '6' day,'MM/dd/yyyy'), 
count(*) 
from data 
where project_id = 'ABC' 
and actual_sale_date >= date_trunc('year',current_date) 
group by rollup((extract(week from actual_sale_date) 
       ,to_char(date_trunc('week', actual_sale_date) + interval '6' day,'MM/dd/yyyy'))) 
+0

謝謝,所以無論函數在'select'級別應用**必須**應用於「羣體」水平呢? –

相關問題