简体   繁体   English

在mysql查询中SUM多个日期范围

[英]SUM multiple date ranges in mysql query

I have a MySql table 'Products' with three columns: 我有一个MySql表'Products'有三列:

Date | Product | Qty

My aim is to SUM the qty of each product for every week. 我的目标是每周提取每种产品的数量。

Getting the SUM between two given dates would be easy: 在两个给定日期之间获得SUM很容易:

SELECT SUM(qty) FROM products WHERE date >= '2010-01-01' AND date < '2011-01-1'

I can generate a list of weeks in Php using something like: 我可以使用以下内容生成Php中的周列表:

$today = date('Y-m-d', strtotime('last week Monday'));
$future = date('Y-m-d', strtotime('+90 days'));

$period = new DatePeriod(
 new DateTime($today),
 new DateInterval('P7D'),
 new DateTime($future)
);
foreach ($period as $key => $value) {
    $dates .= $value->format('Y-m-d');
}

Is there a MySql query that would work to Group By and SUM by dates? 是否有按日期分组依据和SUM的MySql查询? Or would I be better off looping through in Php? 或者我会更好地在Php中循环?

您可以通过类似的组来实现

GROUP BY week(date)

GROUP BY也是如此

SELECT SUM(qty) FROM products GROUP BY WEEK(date);
  • You can use Year() and Week() functions in MySQL, to get the year and week number for a given date. 您可以在MySQL中使用Year()Week()函数来获取给定日期的年份和周数。 Week() function will return week number from 0 to 53. So, you will be needed to use Year() function alongwith, if you have data spanning over multiple years. Week()函数将返回从0到53的周数。因此,如果您的数据跨越多年,则需要使用Year()函数。
  • But then, you will be more interested in knowing the start date and end date for the concerned week. 但是,您将更有兴趣了解相关周的开始日期和结束日期。 This is where we can use a very interesting function DayOfWeek() . 这是我们可以使用非常有趣的函数DayOfWeek() It returns the weekday index for a given date ( 1 = Sunday, 2 = Monday, …, 7 = Saturday ) 它返回给定日期的工作日索引( 1 =星期日,2 =星期一,...,7 =星期六
  • We can use Date_Add() function using the weekday index value and the actual date value, to determine the starting week date and ending week date for a given date. 我们可以使用工作日索引值和实际日期值来使用Date_Add()函数,以确定给定日期的开始周日期和结束周日期。

Try the following ( if the Week starts on Sunday ) : 尝试以下( 如果周从星期日开始 ):

SELECT 
  DATE_ADD(`date`, INTERVAL(1 - DAYOFWEEK(`date`)) DAY) AS week_start_date, 
  DATE_ADD(`date`, INTERVAL(7 - DAYOFWEEK(`date`)) DAY) AS week_end_date, 
  SUM(qty) 
FROM 
  products 
GROUP BY week_start_date, week_end_date 

If the week starts on Monday, another handy function is WeekDay() . 如果周从星期一开始,另一个方便的功能是WeekDay() It returns the weekday index for date ( 0 = Monday, 1 = Tuesday, … 6 = Sunday ). 它返回日期的工作日索引( 0 =星期一,1 =星期二,... 6 =星期日 )。

Try the following ( if the Week starts on Monday ) : 尝试以下( 如果周从星期一开始 ):

SELECT 
  DATE_ADD(`date`, INTERVAL(0 - WEEKDAY(`date`)) DAY) AS week_start_date, 
  DATE_ADD(`date`, INTERVAL(6 - WEEKDAY(`date`)) DAY) AS week_end_date, 
  SUM(qty) 
FROM 
  products 
GROUP BY week_start_date, week_end_date 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM