Amazon Redshift : Best way to compare dates
Asked Answered
M

5

9

I have a sample table in redshift. I want to generate a report with the month wise data. I found the below three ways so far.

  1. trunc(created_at_date) between '2014-06-01' and '2014-06-30'

  2. created_at_date like '2014-06%'

  3. created_at_date >= '2014-06-01 00:00:00' and created_at_date <= '2014-06-30 23:59:59'

    What is the best and optimal way to do so?

Mate answered 27/1, 2015 at 11:45 Comment(0)
S
6

Not the 1st one as it perform unnecessary (unless you really have such unprocessed data) truncate.

 1. trunc(created_at_date) between '2014-06-01' and '2014-06-30';

Definitely not this one for obvious reasons (like)

 2. created_at_date like '2014-06%'

May be this one:

 3. created_at_date >= '2014-06-01 00:00:00' and created_at_date <= '2014-06-30 23:59:59'

However, since the requirement is to generate monthly reports which I would assume to be a recurring task and on multiple data sources, I would suggest creating a one time calendar table.

This table would have mapping of a date to a month value and then you can simply join your source data with that table and group by the "month" column.

P.S. Just realized I replied to a very 'ancient' question :p

Supermarket answered 18/2, 2020 at 8:26 Comment(0)
N
2

How about

created_at_date between to_date('20140601','YYYYMMDD') and to_date('20140630','YYYYMMDD') 
Nonrepresentational answered 27/1, 2015 at 22:33 Comment(1)
My question is which is the best way to compare dates ?Mate
A
2

http://docs.aws.amazon.com/redshift/latest/dg/r_DATE_CMP.html

select caldate, '2008-01-04', date_cmp(caldate,'2008-01-04') from date

Austronesian answered 16/10, 2017 at 22:31 Comment(0)
R
0

I would suggest not to use the second one (with like) at least... For readability and mostly because it reads naturally (at least to me), i usually use some thing like

select col1, col2 , 
   datepart(d, created_at_date) , datepart(mm, created_at_date) 
 from ... 
   group by datepart(d, created_at_date) , datepart(mm, created_at_date) 

If you want to filter by a particular month or year stick in a where datepart(mm, created_at_date) = 6

have a look at http://docs.aws.amazon.com/redshift/latest/dg/r_Dateparts_for_datetime_functions.html

Roath answered 29/1, 2015 at 15:44 Comment(0)
F
0

I prefer a fourth way:

  1. date_trunc('month', created_at_date) = '2014-06-01'
Floria answered 10/3, 2021 at 19:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.