简体   繁体   English

MySql查询每年或每月汇总

[英]MySql Query for Summarizing per Year or per Month

I have the following table structure: table={id,DailyDate,value1,value2} with DailyDate ex. 我有以下表结构:table = {id,DailyDate,value1,value2} with DailyDate ex。 2000-01-01 2000-01-01

How i can get a summarize result firstly per month and secondly per year for each value? 我如何能够每个月首先获得总结结果,然后每年为每个值获得第二个结果?

I was trying the following but it doesn't work 我正在尝试以下但它不起作用

Select Sum(Value1),Year(DailyDate),Month(DailyDate)
From table
Group by Year(DailyDate),Month(DailyDate)
Order by Year(DailyDate),Month(DailyDate)

ty TY

If what you're asking for is subtotals by year, try this: 如果您要求的是按年份小计,请尝试以下方法:

SELECT TheSum, TheYear, COALESCE(TheMonth, CONCAT('Total Year ', TheYear))
FROM (
  SELECT
    SUM(Value1) TheSum,
    YEAR(DailyDate) AS TheYear,
    MONTH(DailyDate) AS TheMonth
  FROM table
  GROUP BY Year(DailyDate), MONTH(DailyDate) WITH ROLLUP) x
WHERE TheYear IS NOT NULL

The inner query uses WITH ROLLUP to generate subtotals by month and a grand total by year. 内部查询使用WITH ROLLUP按月生成小计,按年生成总计。 The outer query formats the year and drops the grand total. 外部查询格式化年份并删除总计。

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

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