SQL Query help

WeTi
WeTi used Ask the Experts™
on
Dear expert

Please read the query below, I need first understand this:
R.DatetimeSentToReceiver < DATEADD(MONTH, 1, @ReminderMonth)
What does it do? And then I want to run query every months like Januari then Feb etc. And I dont want it to count everything from the date 2018-01-01 How to do it?

Thanks


DECLARE
            @ReminderMonth date = '2018-01-01',
            @ReminderNumber1 int = 1,
                  @ReminderNumber2 int = 2;
 
SELECT
(
SELECT COUNT(*)
FROM
            Invoice.Reminder R
WHERE
            R.DatetimeSentToReceiver >= @ReminderMonth
            AND R.DatetimeSentToReceiver < DATEADD(MONTH, 1, @ReminderMonth)
            AND R.ReminderNumber = @ReminderNumber1
                  )As 'Reminder 1',
(
SELECT
            COUNT(*)
FROM
            Invoice.Reminder R
WHERE
            R.DatetimeSentToReceiver >= @ReminderMonth
            AND R.DatetimeSentToReceiver < DATEADD(MONTH, 1, @ReminderMonth)
            AND R.ReminderNumber = @ReminderNumber2
                  )As 'Reminder 2'
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Vitor MontalvãoIT Engineer
Distinguished Expert 2017

Commented:
I need first understand this:
R.DatetimeSentToReceiver < DATEADD(MONTH, 1, @ReminderMonth)
What does it do?
It filters the data to return only rows where the DatetimeSentToReceiver are older than a month or more from the reminder. In your example, before 1st of February of 2018.
Vitor MontalvãoIT Engineer
Distinguished Expert 2017

Commented:
And I dont want it to count everything from the date 2018-01-01 How to do it?
Create a SQL Agent job and copy your code into a new job step by replacing the declaration of the variable @ReminderMonth as the following:
DECLARE 
    @ReminderMonth date = GETDATE(), 

Open in new window

Now  schedule the job to run at the first day of every months and when it runs it will retrieve the first day of the month (GETDATE() function) and execute the rest of the code.
IT Engineer
Distinguished Expert 2017
Commented:
Btw, your code can be improved like this:
DECLARE @ReminderMonth date = GETDATE(), 
 
SELECT
	SUM(CASE ReminderNumber
			WHEN 1 THEN 1 
			ELSE 0
		END) As 'Reminder 1',
	SUM(CASE ReminderNumber
			WHEN 2 THEN 1 
			ELSE 0
		END) As 'Reminder 2'
FROM Invoice.Reminder
WHERE DatetimeSentToReceiver >= @ReminderMonth
	AND DatetimeSentToReceiver < DATEADD(MONTH, 1, @ReminderMonth)

Open in new window

Author

Commented:
Beautiful solution thank you very much!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial