简体   繁体   中英

Bigquery Count Days of Week in Current Date

how do I calculate days of week in this current date?

if I use

select 
date_trunc(salesdate, month)mt,  
count(distinct case when extract(dayofweek from salesdate) in (6,7,1) then salesdate end) weekend, 
count(distinct case when extract(dayofweek from salesdate) not in (6,7,1) then salesdate end) weekday

from `my_table` group by 1

salesdate is the date I got from November-now. and the answer I got

在此处输入图像描述

since this month is not completed yet. the numbers of weekend and weekday is depend on the current date

what I expected is will be

mt           weekend   weekday
2023-01-01   13        18
2022-12-01   14        17

Can you try this:

with my_table as (
select * 
from unnest(generate_date_array('2022-11-01', current_date(), interval 1 day))salesdate
)

select mt
,count(distinct case when extract(dayofweek from salesdate) in (6,7,1) then salesdate end) weekend
,count(distinct case when extract(dayofweek from salesdate) not in (6,7,1) then salesdate end) weekday
 from (
  select 
  date_trunc(salesdate, month)mt,
  LAST_DAY(salesdate, MONTH)ld
  from my_table
  group by mt,ld
  ),
unnest(generate_date_array(mt, ld, interval 1 day))salesdate
group by mt

Query results:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM