我试图通过按周编号分组来显示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
答案 0 :(得分: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')))