[英]How to add first day and last day of month in between query in sql?
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.现在我想对SUM
的数据求和,所以我尝试使用between
功能并获取该月的第一天和最后一天。
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'
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.您可以在没有任何参数的情况下获取last_day()
function 来获取月份的最后一天,并date_format(@mydate, '%Y-%m-01')
来获取月份的第一天。 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);
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.