php mysql中的一个列的条件计数

时间:2016-02-24 12:52:12

标签: php sql

我想计算x持续时间内的所有买卖。我已经尝试了以下查询,但它没有给出正确的结果。

select pair, duration, mode,
       count(case when mode='BUY' then 1 else 0 end) as BUYS,
       count(case when mode='SELL' then 1 else 0 end) as SELLS
from trends
where pair like 'EURAUD '
GROUP BY DURATION, MODE
ORDER BY MODE, DURATION
 duration | mode|BUYS|SELLS
 -------------------------
 1Dy      | BUY | 1  | 1
 1M       | BUY | 18 | 18
 1Wk      | BUY | 1  | 1
 5M       | BUY | 3  | 3
 15M      | SELL| 2  | 2
 1Hr      | SELL| 1  | 1
 1M       | SELL| 25 | 25
 30M      | SELL| 1  | 1
 5M       | SELL| 4  | 4

显示上述结果,这不正确。它显示以下结果

 duration | mode|BUYS|SELLS
 -------------------------
 1Dy      | BUY | 1  | 0
 1M       | BUY | 18 | 0
 1Wk      | BUY | 1  | 0
 5M       | BUY | 3  | 0
 15M      | SELL| 0  | 4
 1Hr      | SELL| 0  | 1
 1M       | SELL| 0  | 25
 30M      | SELL| 0  | 1
 5M       | SELL| 0  | 4

1 个答案:

答案 0 :(得分:0)

您需要sum(),而不是count()

select pair, duration, mode,
       sum(case when mode = 'BUY' then 1 else 0 end) as BUYS,
       sum(case when mode = 'SELL' then 1 else 0 end) as SELLS
from trends
where pair like 'EURAUD '
GROUP BY DURATION, MODE
ORDER BY MODE, DURATION;

COUNT()计算非NULL值的数量。您的case表达式永远不会返回NULL,因此计数始终返回相同的值。我更喜欢使用SUM()