mysql给了我不同的结果

hwazgwia  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(264)

我有以下数据:

+--------------------+-------------+------------------+
| 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           |

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

我想得到 timestampprofit_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)

在这个模拟中,我只有一个包含 profit_loss_type = nett ,所以结果应该是13366。不是10741。

gfttwv5a

gfttwv5a1#

更改为总和>0
sql演示

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) > 0;

相关问题