› MySQL 5.5 Community Server
› MySQL 5.6 Community Server
› Percona Configuration Wizard
› XtraBackup 搭建主从复制
Great Sites on MySQL
› Percona
› MySQL Performance Blog
› Severalnines
推荐管理工具
› Sequel Pro
› phpMyAdmin
推荐书目
› MySQL Cookbook
MySQL 相关项目
› MariaDB
› Drizzle
参考文档
› http://mysql-python.sourceforge.net/MySQLdb.html
lyning
V2EX  ›  MySQL

SQL 根据日期分组统计问题

  •  
  •   lyning · Mar 7, 2016 · 4025 views
    This topic created in 3859 days ago, the information mentioned may be changed or developed.

    mysql

    表 A:
    id | date | count

    需求: 想将表 A 里面的字段 count 按照 当前年 往前 推 11 年 再根据(年 月 日)分组统计
    例如:
    year | yearCount | month | monthcount | day | dayCount
    2016 1000 01 120 02 5
    2016 1000 01 120 03 3
    ...
    2016 1000 12 110 01 10
    ...
    2015 900 01 100 03 5
    ...
    2005 800 01 120 03 3
    ...
    2005 800 12 80 12 7

    我的 sql 是这么写的, 请教(更优化 更好看 更有效率)的写法, 因为我写的这一段 sql 实在不怎么好看, 而且很罗嗦, 可能还存在问题
    SELECT tt.*, DATE_FORMAT(t.date,'%d') day, SUM(t.count) day_count
    FROM A t3,

    (SELECT t.*, DATE_FORMAT(t2.date,'%m') month, SUM(t2.count) month_count
    FROM A t2,
    
        (SELECT YEAR(t.recycle_date) year, SUM(t1.count)/1000 year_count
        FROM A t1 WHERE YEAR(t1.date)>=(YEAR(curdate())-11)
        GROUP BY YEAR(t1.date)) t
    
    WHERE YEAR(t1.date)=re.year 
    GROUP BY DATE_FORMAT(t2.date,'%Y-%m')) tt
    

    WHERE YEAR(t3.date)=tt.year AND MONTH(t3.date)=tt.month
    GROUP BY DATE_FORMAT(t3.date,'%Y-%m-%d')
    ORDER BY tt.year, tt.month, day ASC;

    2 replies  •  2016-03-07 16:03:28 +08:00
    iyaozhen
        1
    iyaozhen  
       Mar 7, 2016
    我一般就统计到日。然后有月和年的需求的话业务层自己处理。这样也比较灵活。
    lyning
        2
    lyning  
    OP
       Mar 7, 2016
    @iyaozhen 哇哦, 这个建议不错
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1058 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 17:43 · PVG 01:43 · LAX 10:43 · JFK 13:43
    ♥ Do have faith in what you're doing.