Mysql 查询 - 月份

Mysql query - month

我是 Mysql 的初学者,我有一个 table 这样的:

create table purchase 
(
    purchase_ID INT primary key,
    purchase_date DATE,
    purchase_price INT
);

Insert into purchase values ('1', '2015-5-30', '10000');
Insert into purchase values ('2', '2016-7-30', '80000');
Insert into purchase values ('3', '2017-8-30', '50000');
Insert into purchase values ('4', '2016-10-30', '90000');

现在的问题是:找出 2016 年哪个月份的销售额最高。

注意:将购买价格视为销售额。

为了找到这个问题的答案,我尝试了这个 SQL 语句:

SELECT
    MAX(purchase_price) AS sales,
    MONTH(purchase_date) 
FROM
    purchase 
WHERE 
    CAST(purchase_date AS date) BETWEEN '2016-01-01' AND '2016-12-30'

得到的结果为

sales   month(purchase_date)
----------------------------
90000         7

但是我在月份中遇到错误,因为第 10 个月的最高销售额不是 7,有人可以对此提出建议吗?

find which month has highest sales for the year 2016

SELECT *
FROM purchase 
WHERE purchase_date BETWEEN '2016-01-01' AND '2016-12-30'
ORDER BY purchase_price DESC
LIMIT 1

要使用 MAXSUM 等,您需要执行 GROUP BY(与 GROUP BY 的聚合查询)

SELECT MAX(purchase_price) as sales, MONTH(purchase_date) as month
from purchase where purchase_date between '2016-01-01' and '2016-12-30'
GROUP BY month
ORDER BY month desc
LIMIT 1

这个查询应该适合你。