0

再会。

在此处检查表的结构。

我想选择:

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 可以在这里找到

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

4

2 回答 2

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;

现场演示。

于 2013-07-05T16:07:55.007 回答
0

如果您愿意考虑更改数据库结构,我建议将金额存储为带符号的值,如果状态为“向上”则为正,如果状态为“向下”则为负。

在这些条件下,您的查询会简单得多。

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 答案中的查询。

于 2013-07-05T17:15:12.383 回答