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 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿