Home > Blockchain >  Bigquery Count Days of Week in Current Date
Bigquery Count Days of Week in Current Date

Time:01-04

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

enter image description here

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

CodePudding user response:

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:

enter image description here

  • Related