简体   繁体   中英

Sql Query - group by month from 1st day up todays date

I have a record set of sales amount daily with different branches. For example

Date             Amount      Branch
01/01/2014         30          A
01/01/2014         30          B
01/02/2014         40          A
01/02/2014         40          B
01/03/2014         30          A
01/03/2014         30          B
up to feb,mar,apr,may,jun,jul,aug

What i want to achieve is to group the record monthly based on todays date day.

For example today is 08/11/2014. the range should be 1st day of the month "1" then i will pick the day today which is 11. So the range for all the months is 1-11. See below sample.

Date Range for query monthly
01/01/2014-01/11/2014
02/01/2014-02/11/2014
03/01/2014-03/11/2014
04/01/2014-04/11/2014
05/01/2014-05/11/2014
06/01/2014-06/11/2014
07/01/2014-07/11/2014
08/01/2014-08/11/2014

Group this date range and get the sum of total sales.

Please help

This should do most of the work:

  SELECT MONTH(date), SUM(amount)
    FROM table_name
   WHERE DAY(date) <= DAY(CURDATE())
     AND date >= YEAR(CURDATE())
GROUP BY MONTH(date);

UPDATE

For the 3 letter month tag, also you'll probably want an ORDER BY to be sure:

  SELECT DATE_FORMAT(date,'%b'), SUM(amount)
    FROM table_name
   WHERE DAY(date) <= DAY(CURDATE())
     AND date >= YEAR(CURDATE())
GROUP BY MONTH(date)
ORDER BY MONTH(date);

You should be able to achieve what you want by using the following MySQL query:

select sum('amount') from 'some_table'
    where dayofmonth('sell_date') >= 1
        and dayofmonth('sell_date') < dayofmonth(currdate())
    group by month('sell_date');

I hope it works, did not have some database to test.

You could eventually also group by branch, by adding an additional , 'branch' before the query's semicolon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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