我想对SQL中的两列求和,如果总和大于0,则将其输出到其中一列,如果小于0,则输出到另一列。
我的代码如下:
SELECT IF(SUM(`processed_quantity_long`,-1*`processed_quantity_short`) > 0,SUM(`processed_quantity_long`,-1*`processed_quantity_short`) AS `Position Long`,SUM(`processed_quantity_long`,-1*`processed_quantity_short`) AS `Position Short`)
From table A
GROUPBY date
它向我返回此错误:
您的SQL语法有错误;检查与您的MariaDB服务器版本相对应的手册以获取正确的语法,以便在第5行的'-1 * {
processed_quantity_short
)> 0,SUM(processed_quantity_long
,-1 *`processed_qua'附近使用
不确定如何解决此错误。
答案 0 :(得分:1)
SUM
不需要两个参数。只需在计算总和之前减去两个数字即可:
SELECT
CASE WHEN SUM(processed_quantity_long - processed_quantity_short) >= 0 THEN SUM(processed_quantity_long - processed_quantity_short) END AS `Position Long`,
CASE WHEN SUM(processed_quantity_long - processed_quantity_short) < 0 THEN SUM(processed_quantity_long - processed_quantity_short) END AS `Position Short`
FROM tablea
GROUP BY date
答案 1 :(得分:0)
如果
,您在里面做错了 SELECT IF(
SUM(processed_quantity_long-processed_quantity_short) > 0,
SUM(`processed_quantity_long`-`processed_quantity_short`) ,
SUM(`processed_quantity_long`-`processed_quantity_short`) AS `Position Short`
) From tableA GROUP BY date
常规if语句如下
SELECT IF(500<1000, "YES", "NO")
或用例
case when SUM(`processed_quantity_long`-`processed_quantity_short`) > 0
then SUM(`processed_quantity_long`-`processed_quantity_short`)
else SUM(`processed_quantity_long`-`processed_quantity_short`) as position
from tableA GROUP BY date
答案 2 :(得分:0)
也许编写代码的最简单方法是:
SELECT GREATEST(SUM(processed_quantity_long - processed_quantity_short), 0) AS Position_Long,
LEAST(SUM(processed_quantity_long - processed_quantity_short), 0) AS Position_Short
FROM tablea
GROUP BY date