我需要什么: SUM(v + t + p),如果m =' 7'和SUM(v + t + p),如果m =' 8',并对其进行排序(通过减去(SUM(v + t + p),如果m =' 8') - SUM (v + t + p)如果m =' 7')。
答案 0 :(得分:1)
这是你正在寻找的一般形式(可能):
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
;
您可以选择多个部分。
更具体......
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
;
编辑: (为你的后兜节省一些时间,希望有用的东西)
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);
编辑:
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
;