简体   繁体   中英

How to do I get the max day of each month in sql/snowflake

I'm trying to return The max day of each month from a data set. I say max because it's based on mon-fri uploads. So if the last day of the month falls on a Saturday(say 10/31/2019) then the last uploaded date will be on the Friday (10/30/2019).

I've tried select max(date) from my_table group by datepart('month',date);

You can use dayofweekiso to get only those monday-friday transactions.

select max(date), month(case when date) from my_table 
where dayofweekiso(date) between 1 and 5
group by year(date), month(date);

Using the snowflake_sample_date there is a date dimension, Small change to MIkes query .. 1--7 looks good

SELECT
MAX(d.d_date) FROM
tpcds_sf10tcl.date_dim d WHERE DAYOFWEEKISO(d.d_date) BETWEEN 1 AND 7 GROUP BY YEAR(d.d_date) , MONTH(d.d_date) ORDER BY MAX(d_date);

QUALIFY can be used to create a rank and filter on it on the fly. So rank on partition by year and month, order by date descending to rank the last days of each month in your table as 1.

SELECT * FROM TABLE
QUALIFY RANK() OVER(PARTITION BY YEAR(DATE), MONTH(DATE) ORDER BY DATE DESC) = 1;

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