WHERE条件下的mysql SUM列

时间:2017-11-15 00:00:31

标签: mysql sum

我试图获得满足条件的所有列的总和。这是我目前的设置

    SELECT 
                      COUNT(order_type = 'BUY') AS buy_fill,
                      COUNT(order_type = 'SELL') AS sell_fill,
                      SUM(btc_total) AS fill_sum
                      FROM fill_orders
                      WHERE coin_id = '$coin'
                      AND time_stamp >= DATE_SUB(NOW(), INTERVAL 55 SECOND)

这就是我现在所拥有的,它计算我有多少种买卖订单,并且也给了我所有订单的总和,但我需要将订单总和分成买入订单和卖出订单。

这是我尝试创作的代码。我已添加(btc_total WHERE order_type ='购买')和SUM(btc_total WHERE order_type ='卖出')

      SELECT 
                            COUNT(order_type = 'BUY') AS buy_fill,
                            COUNT(order_type = 'SELL') AS sell_fill,
                            SUM(btc_total) AS fill_sum,

                            SUM(btc_total WHERE order_type = 'BUY') AS buy_total
                            SUM(btc_total WHERE order_type = 'SELL') AS sell_total
                      FROM fill_orders
                      WHERE coin_id = '$coin'
                      AND time_stamp >= DATE_SUB(NOW(), INTERVAL 55 SECOND)

2 个答案:

答案 0 :(得分:1)

改变这个:

SUM(btc_total WHERE order_type = 'BUY') AS buy_total

到此:

SUM(IF(order_type='BUY',btc_total,NULL)) AS buy_total

MySQL IF()函数将第一个参数计算为布尔值,如果为TRUE,则返回第二个参数,否则返回第三个参数。

将为每一行评估IF(),并且该表达式的返回将由SUM()聚合总计。

或者,使用更多ANSI标准的等价物来实现相同的结果:

SUM(CASE WHEN order_type = 'BUY' THEN btc_total END) AS buy_total

此模式通常称为“条件聚合”。

对于“计数”,我们可以将COUNT替换为SUM,如下所示:

SUM(order_type = 'BUY') AS buy_fill

MySQL将相等比较计算为布尔值,返回1,0或NULL,然后由SUM聚合累加。 (其中包括零和一个,而不仅仅是那些。)

以上相当于

SUM( CASE
     WHEN order_type  = 'BUY' THEN 1
     WHEN order_type <> 'BUY' THEN 0
     ELSE NULL
     END
   ) AS buy_fill

如果我们想要使用COUNT聚合,我们可以这样做:

COUNT(IF(order_type = 'Buy',1,NULL)) AS buy_fill

(我们可以使用任何非空值代替1,并获得相同的结果。)

答案 1 :(得分:1)

“条件聚合”通常包含case expression

SELECT
      COUNT(CASE WHEN order_type = 'BUY' THEN order_type END)      AS buy_fill
    , COUNT(CASE WHEN order_type = 'SELL' THEN order_type END)     AS sell_fill
    , SUM(btc_total)                                               AS fill_sum
    , SUM(CASE WHEN order_type = 'BUY' THEN btc_total ELSE 0 END)  AS buy_total
    , SUM(CASE WHEN order_type = 'SELL' THEN btc_total ELSE 0 END) AS sell_total
FROM fill_orders
WHERE coin_id = '$coin'
AND time_stamp >= DATE_SUB(NOW(), INTERVAL 55 SECOND)