MySQL HAVING给我不同的结果

时间:2018-06-25 07:35:50

标签: mysql

我有此数据:

+--------------------+-------------+------------------+
| timestamp          | profit_loss | profit_loss_type |
+--------------------+-------------+------------------+
| lm58-1527906222477 |  0.00200000 | profit           |
| lm58-1527906222477 | -0.00008617 | fraction         |
| lm58-1527906222477 | -0.00027400 | normal           |
| lm58-1527906222477 |  0.00008617 | nett             |
| lm58-1527906222477 |  0.00027400 | nett             |

| lm99-1527906222888 |  0.00200000 | profit           |
| lm99-1527906222888 | -0.00008617 | fraction         |
| lm99-1527906222888 | -0.00027400 | normal           |

| lm11-1527906222999 |  0.00200000 | profit           |
| lm11-1527906222999 |  0.00008617 | fraction         |
| lm11-1527906222999 |  0.00027400 | normal           |

+--------------------+-------------+------------------+

我想和timestamp一起获得profit_loss < 0,但没有profit_loss_type = 'nett'

所以我期望这样的结果:

+--------------------+
| timestamp          |
+--------------------+
| lm99-1527906222888 |
+--------------------+

这是我的查询,以获取包含timestamp的所有profit_loss < 0

SELECT timestamp
FROM gross_profit
WHERE profit_loss < 0
AND (profit_loss_type = 'normal' OR profit_loss_type = 'fraction')
GROUP BY timestamp

13367 rows in set (0.15 sec)

但是当我添加HAVING时,为什么结果不同?

SELECT timestamp
FROM gross_profit
GROUP BY timestamp
HAVING SUM(CASE WHEN profit_loss_type = 'nett' THEN 1 ELSE 0 END) = 0
AND SUM(CASE WHEN profit_loss < 0 THEN 1 ELSE 0 END) = 1;

10741 rows in set (0.23 sec)

在此模拟中,我只有1个包含profit_loss_type = nett的时间戳,因此结果应为13366。而不是10741。

1 个答案:

答案 0 :(得分:1)

更改为SUM> 0

SQL DEMO

C++