简体   繁体   中英

MySQL query for total number of cars purchased per month

I need a help to find total number of cars purchased based on every month. I have a table(purchase) setup like this (simplified for example):

  sno
  country
  purchased_date(yyyy-mm-dd)
  make
  model

Now I want to generate a report with the total number of cars purchased every month, and here's my query:

SELECT COUNT(`country`), `model`, `make`, `purchase_date`, `country`
FROM charmy_purchase 
WHERE `country` != '' 
GROUP BY model

It produces the wrong report.

Maybe something like this:

SELECT 
    COUNT( `country` ) , 
    `model` , 
    MONTH(purchase_date) AS Month
FROM 
    charmy_purchase 
WHERE 
    `country` != '' 
GROUP BY 
   model,
   MONTH(purchase_date)

EDIT

If you have different years. Then you might consider grouping on year as well. Like this:

SELECT 
    COUNT( `country` ) , 
    `model` , 
    MONTH(purchase_date) AS Month,
    YEAR(purchase_date) AS year
FROM 
    charmy_purchase 
WHERE 
    `country` != '' 
GROUP BY 
   model,
   MONTH(purchase_date),
   YEAR(purchase_date)

Useful references:

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