0

I finding the sum of revenue last month. Currently, I'm filtering by giving where condition. For example if I need last month's data given the current date is '20191111'. My query to get October's data is

Select sum(revenue)
from Table 1
where date between '20191001' and '20191031'

Note : My date column is a string. How can I modify it to fetch the last month's record automatically?

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
user62367
  • 25
  • 5

1 Answers1

0

You're nearly there, although if your date column in the table is currently in String format, I would consider casting that column as a date data type, then using greater than and less than comparisons instead of the between clause.

Try something like the following:

SELECT SUM(revenue)
FROM Table 1
WHERE CAST(date AS DATE) >= '20191001' AND CAST(date AS DATE) < '20191101'

To fetch the last month's revenue automatically, or the total revenue for the month as of the current date, you could use something like the following:

Get the last months revenue:

SELECT SUM(revenue)
FROM Table 1
WHERE MONTH(CAST(date AS DATE)) < (MONTH(GETDATE()) - 1) 
AND MONTH(CAST(date AS DATE)) > (MONTH(GETDATE()) - 2)
Lancelot
  • 3
  • 2