2017-04-04 51 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'级别应用**必须**应用于“群体”水平呢? –

相关问题