【问题标题】:Sum statement counts everything, or northingSum 语句计算所有内容,或向北计算
【发布时间】:2014-01-24 11:28:08
【问题描述】:

我的项目几乎完成了,但我还有一个问题。 我需要使用 sql 代码创建摘要。代码是这样的:

"SELECT SUM(一列的价格), select others FROM blablabla WHERE 条件 1 为真 OR 条件 2 为真 OR 条件 3 为真 GROUP BY blablabla;"

问题是,由于 OR,我无法使用上述内容。每当我使用 OR 时,它会看到例如条件 1 为真,因此他将忽略其余条件,但我需要它们来查看它们是否为真。使用“AND”而不是“OR”的问题导致将结果设置为空,因为这三个并不总是正确的。

所以底线是,我的查询需要计算字段满足条件的列中的一些字段。我使用多个条件,因为有不同种类的产品,但我不知何故不能同时使用条件,因为只要满足一个条件,该语句就会计算所有内容,或者因为它们不能总是对所有三个条件都为真,所以不计算任何内容。

我该如何解决这个问题?

谢谢

【问题讨论】:

  • 试试SELECT SUM(CASE prices_of_a_column WHEN NULL THEN 0 ELSE prices_of_a_column END), ...

标签: sql sum conditional-statements where


【解决方案1】:
SELECT SUM(prices column) as Total
FROM yourTable
WHERE condition1 is true
GROUP BY columnBLabla

UNION ALL

SELECT SUM(prices column)
FROM yourTable
WHERE condition2 is true
GROUP BY columnBLabla

UNION ALL

SELECT SUM(prices column)
FROM yourTable
WHERE condition3 is true
GROUP BY columnBLabla

结果

Total

100 -- total price when condition 1 is true
230 -- total price when condition2 is true
900 -- total price when condition 3 is true

【讨论】:

  • 我不认为我可以使用它,因为我选择了除总和之外的多个列
【解决方案2】:

我不确定我是否完全理解了这个问题,我想这就是你要找的

SELECT SUM(prices of a column) 
FROM blablabla 
WHERE 
(condintion 1 is true OR condition 2 is true)
AND 
(condintion 1 is true OR condition 3 is true) 
AND 
(condintion 2 is true OR condition 3 is true) 
GROUP BY blablabla;

可能是

SELECT SUM(prices of a column) 
FROM blablabla 
WHERE 
(condintion 1 is true AND condition 2 is true)
OR 
(condintion 1 is true AND condition 3 is true) 
OR 
(condintion 2 is true AND condition 3 is true) 
GROUP BY blablabla;

【讨论】:

    【解决方案3】:

    我可能会误解,但是,你能用一个案例陈述吗?您可以将每个条件放在其自己的“当 X 为真 A”语句中。然后通过改变/不改变 A,您可以创建类别进行总结。

    【讨论】:

      【解决方案4】:

      这个怎么样?

      SELECT
        SUM(CASE WHEN condition1 THEN prices_of_a_column ELSE 0 END) AS prices1,
        SUM(CASE WHEN condition2 THEN prices_of_a_column ELSE 0 END) AS prices2,
        SUM(CASE WHEN condition3 THEN prices_of_a_column ELSE 0 END) AS prices3
      FROM blabla
      GROUP BY blabla
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        • 2021-11-24
        • 1970-01-01
        • 2012-03-04
        • 1970-01-01
        • 2016-08-25
        • 1970-01-01
        相关资源
        最近更新 更多