我有以下数据:
+--------------------+-------------+------------------+
| 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)
在这个模拟中,我只有一个包含 profit_loss_type = nett
,所以结果应该是13366。不是10741。
1条答案
按热度按时间gfttwv5a1#
更改为总和>0
sql演示