V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
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
zl8723
V2EX  ›  MySQL

求教,这个需求下,统计SQL如何写?

  •  
  •   zl8723 ·
    eagleon · Jun 4, 2013 · 3756 views
    This topic created in 4712 days ago, the information mentioned may be changed or developed.
    表:temp
    id branch_name score level
    1 成都 1 1
    2 重庆 1 1
    3 成都 2 2

    统计结果:

         level=1  level=2  合计
    机构 [score 次数] [score 次数] [score 次数]

    也就是说:统计在不同level下score的总分值和次数。

    写来写去,都在绕圈子,求指教!单起来写,没啥问题,不知道咋合起来。
    Supplement 1  ·  Jun 4, 2013
    4 replies    1970-01-01 08:00:00 +08:00
    lichao
        1
    lichao  
       Jun 4, 2013
    select branch_name,

    sum(case level when 1 then 1 else 0 end),
    sum(case level when 2 then 1 else 0 end),

    sum(case level when 1 then 1 else 0 end)
    +
    sum(case level when 2 then 1 else 0 end)

    group by branch_name
    lichao
        2
    lichao  
       Jun 4, 2013   ❤️ 1
    select branch_name,

    sum(case level when 1 then score else 0 end),
    sum(case level when 1 then 1 else 0 end),

    sum(case level when 2 then score else 0 end),
    sum(case level when 2 then 1 else 0 end),

    sum(case level when 1 then score else 0 end)
    +
    sum(case level when 2 then score else 0 end),

    sum(case level when 1 then 1 else 0 end)
    +
    sum(case level when 2 then 1 else 0 end)

    group by branch_name
    zl8723
        3
    zl8723  
    OP
       Jun 4, 2013
    @lichao 谢谢,感谢已送出。
    zl8723
        4
    zl8723  
    OP
       Jun 4, 2013
    select branch_name,
    sum(case level when 1 then final_score else 0 end) z_s,
    count(case level when 1 then final_score else null end) z_c,

    sum(case level when 2 then final_score else 0 end) f_s,
    count(case level when 2 then final_score else null end) f_c,

    sum( final_score) t_s,
    count(final_score) t_c
    from temp
    group by branch_name
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1015 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:09 · PVG 06:09 · LAX 15:09 · JFK 18:09
    ♥ Do have faith in what you're doing.