如何在mysql中添加两个求和值

时间:2018-06-28 10:07:46

标签: mysql mysqli sum

是否可以像下面所示的查询一样在mysql中添加两个求和值(图1)?

我在下面有查询,并且我想添加数量和亲。

图1

    SELECT  

    SUM(CASE WHEN value > 0 AND xp = 0 THEN 1 ELSE 0 END) AS qty,
    SUM(CASE WHEN value > 1 AND xp = 2 THEN 1 ELSE 0 END) AS pro

    SUM(pro + qty)

    FROM OrderDetails;

我将需要在整个查询中多次使用qty和pro,所以我不想编写图2

中所示的查询

图2

    SELECT  

    SUM(
    SUM(CASE WHEN value > 0 AND xp = 0 THEN 1 ELSE 0 END)
    + 
    SUM(CASE WHEN value > 1 AND xp = 2 THEN 1 ELSE 0 END)
    )

    FROM OrderDetails;

已编辑

在整个查询中多次使用 qty pro 的意思是类似以下内容。

查询示例一-我正在尝试做的是,在整个查询过程中,我可以在sum(pro + qty)having (qty > 0 AND pro > 0)之类的地方多次重复使用pro和pro,无需重写整个sum语句。

SELECT  

SUM(CASE WHEN value > 0 AND xp = 0 THEN 1 ELSE 0 END) AS qty,
SUM(CASE WHEN value > 1 AND xp = 2 THEN 1 ELSE 0 END) AS pro

SUM((pro + qty)/100)

FROM OrderDetails

GROUP BY value

HAVING (
       qty > 2
       AND
       pro > 2
       )
;

查询示例2 -我目前要做的是,必须多次重写SUM(CASE WHEN value > 0 AND xp = 0 THEN 1 ELSE 0 END)而不是简单的 qty < / strong>或 pro ,如上面的查询

SELECT  

SUM(CASE WHEN value > 0 AND xp = 0 THEN 1 ELSE 0 END) AS qty,
SUM(CASE WHEN value > 1 AND xp = 2 THEN 1 ELSE 0 END) AS pro

SUM((
     SUM(CASE WHEN value > 0 AND xp = 0 THEN 1 ELSE 0 END)
      +
     SUM(CASE WHEN value > 1 AND xp = 2 THEN 1 ELSE 0 END)
)/100)

FROM OrderDetails

GROUP BY value

HAVING (
       SUM(CASE WHEN value > 0 AND xp = 0 THEN 1 ELSE 0 END) > 2
       AND
       SUM(CASE WHEN value > 1 AND xp = 2 THEN 1 ELSE 0 END) > 2
       )
;

在像SUM(pro + qty)这样的示例中定义一次后,无法添加SUM(CASE WHEN value > 0 AND xp = 0 THEN 1 ELSE 0 END) AS qty

2 个答案:

答案 0 :(得分:0)

您可以使用以下查询进行计算。

SELECT  

SUM(CASE WHEN value > 0 AND xp = 0 THEN 1 ELSE 0 END) AS qty,
SUM(CASE WHEN value > 1 AND xp = 2 THEN 1 ELSE 0 END) AS pro,
SUM(CASE 
        WHEN value > 0 AND xp = 0 THEN 1
        WHEN value > 1 AND xp = 2 THEN 1 
    ELSE 0 END) AS qtyProSum
FROM OrderDetails;

答案 1 :(得分:0)

为以下查询创建视图并随时使用

SELECT  
    SUM(CASE WHEN value > 0 AND xp = 0 THEN 1 ELSE 0 END) AS qty,
    SUM(CASE WHEN value > 1 AND xp = 2 THEN 1 ELSE 0 END) AS pro
    FROM OrderDetails;