Convert DATEDIFF from SQL Server to redshift - sql

I have script for SQL Server that I need to convert to redshift.
Here is part of it, where I have problem with
LEFT JOIN
(SELECT
cog.ClientId,
MAX(CASE me.metrickey WHEN 'contacts-employee_active_count_day_org' THEN mu.value ELSE 0 END) AS ActiveEmployees
FROM
public.module_utilization mu
JOIN
(SELECT
me.id,
me.ChannelId + '-' + me.metrickey AS MetricKey
FROM
public.module_metric me) AS me ON me.id = mu.metricid
LEFT JOIN
public.contacts_client_organization cog ON cog.clientorganizationid = mu.organizationid
WHERE
mu.dy >= DATEADD(Day, -30, GETDATE())
AND me.metrickey IN ('contacts-employee_active_count_day_org')
GROUP BY
cog.clientid) metrics ON metrics.ClientId = be.clientid
WHERE
be.organizationid = 65277
AND be.timeworkedfrom >= DATEADD(MONTH, -6, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0))
AND be.timeworkedfrom < TO_CHAR(DATE_TRUNC('month', GETDATE()), 'MM/DD/YYYY')
AND be.isdeleted IS NULL
AND be.isvoid IS NULL
At this line
AND be.timeworkedfrom >= DATEADD(MONTH, -6, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0))
I get this error
Invalid operation: function pg_catalog.date_diff("unknown", integer, timestamp without time zone) does not exist;
As I understood it because of 0
How I can fix this stuff?

Your highlighted WHERE clause logic is comparing timeworkedfrom to a date six months earlier than the first of the current month. You may change this:
AND be.timeworkedfrom >= DATEADD(MONTH, -6, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0))
to this:
AND be.timeworkedfrom >= date_trunc('month', current_date) - interval '6 month'

Related

Get records of last 2 months (current year), and last month(last year)

I need to get records of last 2 months and last month(last year) based on my table field paidDate, using SQL server 2016.
Suppose, I run the query on Feb 1st/2nd, 2020. I need the monthly data from December 2019, January 2020, as well as January 2019.
What's the SQL query for this? Is it possible to club all of these scenario into one?
Then for the previous 2 months the paidDate would be :
A) Higher or equal than the first day of 2 months ago
B) Lower than the first day of the current month.
Similar for the month of a year ago.
So try something like this:
SELECT *
FROM YourTable
WHERE
(
paidDate >= DATEADD(month, -2, DATEADD(month, DATEDIFF(month, 0, GetDate()), 0))
AND paidDate < DATEADD(month, DATEDIFF(month, 0, GetDate()), 0)
)
OR
(
paidDate >= DATEADD(month, -13, DATEADD(month, DATEDIFF(month, 0, GetDate()), 0))
AND paidDate < DATEADD(year, -1, DATEADD(month, DATEDIFF(month, 0, GetDate()), 0))
)
LukStorm has the better answer in terms of performance (and I've upvoted it). But if you want complete months and don't care about indexing, then I would suggest datediff():
where datediff(month, paiddate, getdate()) in (1, 2, 13)
This gets the complete months that are 1 month, 2 months, and 13 months in the past.
You can try the logic as below-
SELECT *
FROM your_table
WHERE
(
YEAR(paidDate) = YEAR(DATEADD(MM,-1, getdate()))
AND
MONTH(paidDate) = MONTH(DATEADD(MM,-1, getdate()))
)
OR
(
YEAR(paidDate) = YEAR(DATEADD(MM,-2, getdate()))
AND
MONTH(paidDate) = MONTH(DATEADD(MM,-2, getdate()))
)
OR
(
YEAR(paidDate) = YEAR(DATEADD(MM,-13, getdate()))
AND
MONTH(paidDate) = MONTH(DATEADD(MM,-13, getdate()))
)

Retrieving last months data when last month is also last year?

I have the following Where clause in several queries. This successfully retrieves the past months data. Now the year has changed, the query can't find any data (December 2018 hasn't happened yet!). How can I change the Where clause to overcome this?
select *
from somedatabase a
WHERE DATEPART(m, a.meetDate) = DATEPART(m, DATEADD(m, -1, getdate()))
and DATEPART(yyyy, a.meetDate) = DATEPART(yyyy, getdate())
Many thanks and any assistance very gratefully received.
My normal way of rounding down to the start of the current month is:
DATEADD(month, DATEDIFF(month, 0, getDate()), 0)
Find out how many whole months there have been since date 0
Then add that many months to date 0
Always gives the start of the month (as date 0 is the start of a month)
Is not affected by leap year, year boundaries, months of various length, etc
This then allows me to do things like...
WHERE
a.meetDate >= DATEADD(month, DATEDIFF(month, 0, getDate()) - 1, 0) -- start of last month
AND a.meetDate < DATEADD(month, DATEDIFF(month, 0, getDate()) , 0) -- start of this month
By having the calculations on the right hand side you make maximum use of indexes.
Here is one way:
WHERE DATEPART(month, a.meetDate) = DATEPART(month, DATEADD(m, -1, getdate())) AND
DATEPART(year, a.meetDate) = DATEPART(year, DATEADD(m, -1, getdate()))
That is, subtract one month for both comparisons.
Actually, a simpler way is to use the strange rules of DATE_DIFF():
WHERE DATEDIFF(month, a.meetDate, getdate()) = 1
Neither of these can make use of an index. For that, the expression is a little more complicated:
WHERE a.meetDate >= DATEFROMPARTS(YEAR(DATEADD(MONTH, -1, GETDATE()),
MONTH(DATEADD(MONTH, -1, GETDATE()),
1) AND
a.meetDate < DATEADD(DAY, 1 - DAY(GETDATE()), CAST(GETDATE() as DATE))

6 month rolling data

This query is currently pulling back 6 month data, so if I run it today I get data from 01/03/2016 to 06/09/2016. What I would like is the data to stop at 31/08/2016.
And then the following month start at 01/04/2016 to 30/09/2016 and so on.
Many thanks
select i.Date
from table as i
where i.Date >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0)
order by i.Date desc
Try :
select i.Date
from table as i
where i.Date between
Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0)
AND DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, 0)
order by i.Date desc

How to get the 'yesterday' business day in sql

I have a query that gets the yesterday records, but I want that in monday I be able to get the records from friday, not sunday.
Here what I have so far:
select * from tb_interaction
where
(DateInteraction >= DATEADD(day, DATEDIFF(day, 1, GETDATE()), 0)) AND
(DateInteraction < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
Any suggestions?
Thanks!
If your settings are set for English, then you can do:
select i.*
from tb_interaction i cross join
(select (case when datename(getdate()) = 'Monday' then 3
when datename(getdate()) = 'Sunday' then 2
else 1
end) as diff
) x
where DateInteraction >= dateadd(day, - diff - 1, cast(getdate() as date)) and
DateInteraction < dateadd(day, - diff, cast(getdate() as date))

Does SQL automatically calculate month to month start and end dates?

I am trying to get total amount of sales sold in 1 month. For example, from 4/1/15 - 4/30/15.
I am getting a span of 3/30/15 - 4/30/15.
Here is my SQL:
SELECT Customer.custno
, Customer.enteredDate AS 'Date Entered'
, COUNT(BasicPolInfo.polid) AS 'Number of Policies'
, SUM(COUNT(BasicPolInfo.polid)) OVER (ORDER BY Customer.custno ROWS
BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS TotalAmount
FROM Customer
INNER JOIN BasicPolInfo ON Customer.custid = BasicPolInfo.custid
WHERE BasicPolInfo.polid IS NOT NULL
AND Customer.firstname IS NOT NULL
AND Customer.enteredDate BETWEEN DATEADD(MONTH, -1, GETDATE()) AND
DATEADD(MONTH, 0, GETDATE())
GROUP BY Customer.custno
, Customer.firstname
, Customer.lastname
, Customer.entereddate
ORDER BY Customer.enteredDate ASC
The results I am getting are from the dates 2015-04-30 to 2015-03-30. I am trying to get 2015-04-30 to 2015-04-01.
And for the next month to also be from 2015-05-31 to 2015-05-01
Any help would be appreciated! Thank you!
Since you are on 2012 you can use EOMONTH()
WHERE Customer.enteredDate >= DATEADD(DAY, 1, EOMONTH(GETDATE(), -1))
AND < DATEADD(DAY, 1, EOMONTH(GETDATE()))
or you could match the month and year only.
where month(Customer.enteredDate) = month(getDate())
and year(Customer.enteredDate) = year(getDate())
Customer.enteredDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, current_timestamp), 0)
AND Customer.enteredDate < DATEADD(MONTH, DATEDIFF(MONTH, 0, current_timestamp) + 1, 0)