Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get price by month in mysql

I need to get the total price per month.

I have

  • inited_time (ex. 20160530105130)
  • first_payment_price
  • deleted

I tried grouping by inited_time

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT inited_time, DATE_FORMAT(inited_time, '%c') as month, SUM(first_payment_price) as price
FROM some_table
WHERE inited_time > 0 AND deleted = 0
GROUP BY inited_time

But it doesn’t sum them together.
ex of result:

[
  {
    "inited_time": 20160530105130,
    "month": "5",
    "price": 25000.00
  },
  {
    "inited_time": 20160530105157,
    "month": "5",
    "price": 100000.00
  },
  {
    "inited_time": 20160610000002,
    "month": "6",
    "price": 75000.00
  },
  {
    "inited_time": 20160617000001,
    "month": "6",
    "price": 50000.00
  },
  {
    "inited_time": 20160701000001,
    "month": "7",
    "price": 80000.00
  },
  {
    "inited_time": 20160702000001,
    "month": "7",
    "price": 200000.00
  }
]

>Solution :

Ideally the inited_time column would be a format date or timestamp. Assuming it is fixed width, we can aggregate by month using division and modulus on this column to isolate the month number:

SELECT FLOOR(inited_time / 100000000) % 100 AS month, SUM(first_payment_price) AS price
FROM some_table
WHERE inited_time > 0 AND deleted = 0
GROUP BY 1;

Assuming you might have multiple years in your data set and you would want to report each year month separately, we can try using STR_TO_DATE followed by DATE_FORMAT:

SELECT DATE_FORMAT(STR_TO_DATE(inited_time, '%Y%m%d%H%i%s'), '%Y-%m') AS ym,
       SUM(first_payment_price) AS price
FROM some_table
WHERE inited_time > 0 AND deleted = 0
GROUP BY 1
ORDER BY 1;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading