如何写出正确的ORDER BY ...在SQL中选择DESC?

时间:2013-07-05 15:43:26

标签: mysql

美好的一天。

检查表here的结构。

我想选择:

select `idn` order by sum DESC,
where sum = (value amount where type = marks and status = up) - (value amount where type = marks and status = down)

为此,我使用SQL:

select idn from Balans as outerB WHERE idn ! = '' group by idn order by 
ifnull((select sum(innerB.amount) from Balans as innerB 
    where innerB.idn = outerB.idn 
    and type='up'), 0) -
ifnull((select sum(innerB.amount) from Balans as innerB 
    where innerB.idn = outerB.idn 
    and type='down'), 0) DESC
limit 5

但是在SQL中没有正确ORDER by ... DESC

例如在我的例子中,结果应该是:

187113012

6299927

可以找到测试SQL here

请告诉我如何编写正确的SQL select?

2 个答案:

答案 0 :(得分:1)

如何使用CASE

  SELECT idn,
         (SUM(CASE WHEN type = 'marks' AND status = 'up' THEN amount ELSE 0 END)-
         SUM(CASE WHEN type = 'marks' AND status = 'down' THEN amount ELSE 0 END)) 
         AS result
    FROM Balans b
   WHERE idn != ''
GROUP BY idn
ORDER BY result DESC
   LIMIT 5;

<强> Live DEMO.

答案 1 :(得分:0)

如果您愿意考虑更改数据库结构,我建议将金额存储为有符号值,如果状态为“up”则为正值如果状态为“关闭”,则为负数。

在这些情况下,您的查询会更简单。

SELECT idn, SUM(amount) as total
FROM Balans as outerB 
WHERE idn !='' AND type = 'marks'
GROUP BY idn 
ORDER BY total desc
LIMIT 5

但请注意,这不会返回表中没有任何“标记”的记录。如果您需要支持,那么我认为您回到使用CASE操作,类似于Prix答案中的查询。