2

I have a query like this.

SELECT IFNULL(SUM(price),0) as total FROM table1
WHERE table1.id= 33 AND start_time BETWEEN '2019-09-1' AND '2019-09-11'

This works fine. Now I want to SUM the data of a month so I tried to use the between feature and get first day and last day of the month.

SELECT IFNULL(SUM(price),0) as total FROM table1 
WHERE table1.id = 33 AND start_time BETWEEN (SELECT DATEADD(month, DATEDIFF(month, 
'2019-09-15'), 0) AND '2019-09-11'

I used this ref

Sachin Shah
  • 4,503
  • 3
  • 23
  • 50

2 Answers2

2

You can get last_day() function without any argument to get the last day of month, and date_format(@mydate, '%Y-%m-01') to get the first day of the month. So, use :

set @mydate='2019-09-15';

select ifnull(sum(price),0) as total 
  from table1 
 where id = 33 
   and start_time between date_format(@mydate, '%Y-%m-01') and last_day(@mydate);
Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
0

You can calculate the first day of the month by subtracting the day of the month and adding one day:

SELECT IFNULL(SUM(price), 0) as total
FROM table1 
WHERE table1.id = 33 AND
      start_time >= date('2019-09-15') + interval (1 - day(date('2019-09-15'))) day and
      start_time < date('2019-09-15')
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786