如何在查询中通过Sum函数添加订单?

时间:2015-05-26 12:05:03

标签: sql-server sql-order-by

我只是有这个查询,我想通过sum函数的结果添加其记录的顺序,如何添加?

 Select bus.trans_comp_id, 
 SUM(bus.passengers*trips.cost) 
 From bus inner join trips on bus.ID=trips.bus_id 
 group by bus.trans_comp_id 

输出这个:

trans_comp_id  
 1)   1:412000.00
 2)   2:75000.00

我想用desc命令将其输出:

trans_comp_id  
 2)   2:75000.00
 1)   1:412000.00

2 个答案:

答案 0 :(得分:1)

您只需将SUM功能添加到ORDER BY caluse:

即可
Select bus.trans_comp_id, 
 SUM(bus.passengers*trips.cost) 
 From bus inner join trips on bus.ID=trips.bus_id 
 group by bus.trans_comp_id 
 order by SUM(bus.passengers*trips.cost) desc

答案 1 :(得分:1)

只需添加一个ORDER BY子句,该子句使用SELECT子句中定义的计算值的别名:

 SELECT bus.trans_comp_id, 
        SUM(bus.passengers*trips.cost) AS s
 FROM bus 
 INNER JOIN trips ON bus.ID=trips.bus_id 
 GROUP BY bus.trans_comp_id
 ORDER BY s DESC