3

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!

AHiggins
  • 7,029
  • 6
  • 36
  • 54
BarcodePiglet
  • 119
  • 1
  • 8
  • http://stackoverflow.com/questions/11743810/how-to-get-first-and-last-day-of-previous-month-with-timestamp-in-sql-server – Tony Hinkle Apr 30 '15 at 19:17

2 Answers2

3

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())
SQLChao
  • 7,709
  • 1
  • 17
  • 32
1
Customer.enteredDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, current_timestamp), 0) 
AND  Customer.enteredDate < DATEADD(MONTH, DATEDIFF(MONTH, 0, current_timestamp) + 1, 0) 
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794