简体   繁体   English

如何在MySQL中发现每月的每一天的总和?

[英]How to discover the sum of each day of a month in MySQL?

Lets suppose we have a table (for example sales ) with three fields id (int, primary), price (double), date (datetime). 假设我们有一个表(例如sales ),其中包含三个字段id (int,primary), price (双精度), date (日期时间)。

How can we get the sum of the price attribute to each day of the current month? 我们如何获得当月每一天的price属性总和?

And to the last month? 到最后一个月?

I need a return with something similar too: 我也需要类似的退货:

February 二月

01        02        03        04        ...        30
101.1     233.43    1232.42  3232.21             121.23

April 四月

01        02        03        04        ...        30        31
11.1     23.43      122.42   332.21              121.23    2323.32

How could we perform this? 我们该如何执行呢?

Please give me a SQL as example. 请给我一个SQL作为例子。

I thinking to write a method to discover the number of days of the month and than create the SQL iteratively, but I think this isn't the best way. 我想写一种方法来发现一个月中的天数,而不是迭代地创建SQL,但是我认为这不是最好的方法。

You actually want to do a pivot: 您实际上想做一个枢轴:

select year(date), month(date),
       sum(case when day(date) = 1 then price end) as price_01,
       sum(case when day(date) = 2 then price end) as price_02,
       . . .
       sum(case when day(date) = 31 then price end) as price_31
from sales
group by month(date), year(date)

Then add a where clause for the dates that you want. 然后为您想要的日期添加一个where子句。 Something like: 就像是:

where month(date) = month(now())

Collecting all ideas (thx @MarcB, @Stephan, @GordonLinoff) the SQL bellows is what I'm looking for: 收集所有想法(thx @ MarcB,@ Stephan,@ GordonLinoff)是我要查找的SQL波纹管:

February 二月

SELECT
    SUM(price) AS daySum
FROM
    sales
WHERE
    date BETWEEN DATE_FORMAT(NOW() - INTERVAL 2 MONTH,'%Y-%m-01 00:00:00') AND DATE_FORMAT(LAST_DAY(NOW() - INTERVAL 2 MONTH),'%Y-%m-%d 23:59:59')
GROUP BY
    YEAR(date),
    MONTH(date),
    DAY(date)

April (we are currently at April month) 四月 (我们现在是四月)

SELECT
    SUM(price) AS daySum
FROM
    sales
WHERE
    date BETWEEN DATE_FORMAT(NOW(),'%Y-%m-01 00:00:00') AND DATE_FORMAT(LAST_DAY(NOW()),'%Y-%m-%d 23:59:59')
GROUP BY
    YEAR(date),
    MONTH(date),
    DAY(date)

Thx a lot. 多谢。

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

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