douang1243 2015-08-12 00:05
浏览 114
已采纳

MySQL SUM,ORDER BY等

I have this table:
Table

What I need: SUM(v+t+p) if m = '7' and SUM(v+t+p) if m = '8', and order it (by subtract (SUM(v+t+p) if m = '8')-SUM(v+t+p) if m = '7').

  • 写回答

1条回答 默认 最新

  • doutang1884 2015-08-12 00:11
    关注

    This is a very general form of what you are looking for (probably):

    SELECT [somestuff?] 
    , SUM(IF([condition1], [calculation1], 0) AS X1
    , SUM(IF([condition2], [calculation2], 0) AS X2
    FROM theTable
    WHERE [something]
    GROUP BY [something else]
    ORDER BY X1 - X2
    ;
    

    Several sections are possibly optional for you.

    To be more specific...

    SELECT SUM(IF(m = '8', v+t+p, 0) AS sum8
    , SUM(IF(m = '7', v+t+p, 0) AS sum7
    FROM theTable
    ORDER BY sum8-sum7  // This ORDER BY won't really do anything; 
                        // there is only one row since we didn't 
                        // GROUP BY anything
    ;
    

    Edit: (for your back pocket to save some time, hopefully something useful)

    create table thing
    (   id int auto_increment primary key,
        n int not null,
        m int not null,
        v int not null,
        t int not null,
        p int not null
    );
    
    insert thing(n,m,v,t,p) values (2,8,0,0,0);
    insert thing(n,m,v,t,p) values (14,8,0,0,0);
    insert thing(n,m,v,t,p) values (48,7,123,123,123);
    insert thing(n,m,v,t,p) values (48,8,12,1,2);
    insert thing(n,m,v,t,p) values (390,8,0,0,0);
    

    Edit:

    SELECT n
    , SUM(IF(m = '8', v+t+p, 0) AS sum8
    , SUM(IF(m = '7', v+t+p, 0) AS sum7
    , SUM(IF(m = '8', v+t+p, 0)
      - SUM(IF(m = '7', v+t+p, 0) AS sumDiff
    FROM the_table
    GROUP BY n
    ORDER BY sumDiff
    ;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝