简体   繁体   English

如何在 sql 的查询之间添加一个月的第一天和最后一天?

[英]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'

I used this ref我用了这个参考

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.

相关问题 SQL 查询-选择一个月中每一天的第一条和最后一条记录 - SQL query - selecting first and last record of each day in a month 如何从SQL中的给定月份和年份中获取月份的第一天和最后一天 - How to get the First day and last day of the month from given month and year in sql SQL-一个月的最后一天 - SQL - Last Day of Month mysql“之间”查询包括第一天和最后一天 - mysql "between and" query including the first day and the last day 有没有办法获得上个月的第一天和当月的最后一天? - Is there a way to get the First day of the previous month and Last day of current month? SQL查询返回与当前日期或当月最后一天匹配的行 - SQL query to return rows that match current or last day of month SQL查询,用于获取一个月中的每个第一个事件(按日期时间字段) - SQL query for fetching every first event (by datetime field) in day of a month MySQL:选择上个月的第一天和最后一天 - MySQL: Select with first and last day of previous month 在 MariaDb 查询中,给定年份、月份和星期,如何获取一周中的第一天的星期几? - How to get the day of month, of the first day of a week, given the year the month and the week in a MariaDb query? 如何查询开始日期/月份和结束日期/月份之间的价格 - How do i query the price between a start day/month and end day/month
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM